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

时间:2015-12-10 08:34:40

标签: php mysql database

我想检查数据库print false中是否已存在用户ID

CREATE TABLE [dbo].[TblPerson](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [name] [nvarchar](30) NULL,
    [Family] [nvarchar](40) NULL,
    [address] [nvarchar](200) NULL,
    [MeliCode] [char](10) NOT NULL,
    [IsActive] [bit] NULL CONSTRAINT [DF_TblPerson_IsActive]  DEFAULT ((0)),
    [Count] [int] NULL CONSTRAINT [DF_TblPerson_Count]  DEFAULT ((0)),
 CONSTRAINT [PK_TblPerson] PRIMARY KEY CLUSTERED 
(

4 个答案:

答案 0 :(得分:0)

如果你得到任何结果,只需进行计数并测试 如果您得到结果,则您已在数据库中拥有该标识,
如果你没有得到任何结果,则不存在id。

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

还有一件事,你应该从it has been deprecated开始远离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";
}

答案 1 :(得分:0)

你的代码有bug,试试这个:

    $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";
 }

答案 2 :(得分:0)

为什么要仔细检查?如果您的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';
}

答案 3 :(得分:0)

要检查db中是否已存在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";
 }