检查用户id已存在于数据库Mysql中


Check user id Already exist in database Mysql

我想检查数据库中是否已经存在用户id打印错误

$token  = "token";
 $data = json_decode(get_html("https://graph.facebook.com/$user->id&access_token=$token"))->data;
  $id = echo "".$user->id;
  $result = mysql_query("SELECT * FROM token_all WHERE id = $id"); 
 while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
 $checkid = row[id];
  }
  if ($id == $checkid){
echo "true";
 }else{
echo "false";
 }

只需进行计数并测试是否得到任何结果
如果得到结果,则数据库中已经有id,
如果你没有得到任何结果,id就不在那里。

此外,我删除了$id = echo "" . $user->id;,因为我们可以在查询中直接使用$user->id

还有一件事,您应该远离mysql_*API,因为它已经被弃用,而应该转向mysqli_*或更好的PDO

$token  = "token";
$data = json_decode(get_html("https://graph.facebook.com/$user->id&access_token=$token"))->data;
$result = mysql_query("SELECT * FROM token_all WHERE id = " . $user->id); 
$count = mysql_num_rows($result); // edited here
if ($count > 0){
    echo "ID already exists";
}else{
    echo "ID doesn't exist";
}

您的代码有错误,请尝试以下操作:

    $token  = "token";
 $data = json_decode(get_html("https://graph.facebook.com/$user->id&access_token=$token"))->data;
  $id = $user->id;
  $result = mysql_query("SELECT * FROM token_all WHERE id = $id"); 
 while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
 $checkid = $row['id'];
  }
  if ($id == $checkid){
echo "true";
 }else{
echo "false";
 }

为什么要双重检查?如果sql返回结果,则id存在。

$id = $user->id;
$result = mysql_query("SELECT * FROM token_all WHERE id = '" . $id . "'"); 
if (mysql_num_rows($result) > 0)
{
    echo 'TRUE';
}
else
{
    echo 'FALSE';
}

要检查数据库中是否已经存在id,只需要检查其计数。请检查以下代码。

 $token  = "token";
 $data = json_decode(get_html("https://graph.facebook.com/$user->id&access_token=$token"))->data;
 $id = echo "".$user->id;
 $result = mysql_query("SELECT * FROM token_all WHERE id = $id"); 
 $count_user=mysql_num_rows($result); // this will give you the count
 if($count_user >= 1 ) { // if this id is already present in the db
     echo "user already exists";
 }
 else {
     echo "user not exists";
 }