如果存在值,则在数据库中搜索

时间:2014-03-29 10:44:49

标签: php database

我试图检查数据库中的特定值(id),如果存在,则会向用户显示数据存在的消息。 我最近提出这个问题,但它不起作用:

if (isset($_POST['id'])) 
    $id = mysql_real_escape_string(trim($_POST['id']));
} else {
    die("Try not to mess around bro!");
}

$query = mysql_query("SELECT id FROM members WHERE id='$id'");
if (!$query) {
    die('Query failed to execute for some reason');
}
if (mysql_num_rows($query) > 0) {
    echo "this user already exists in the database!";
}

虽然数据库中存在一个值,但没有显示任何消息,并确保代码正确..任何人都可以帮助我吗?提前谢谢

4 个答案:

答案 0 :(得分:0)

    if (isset($_POST['id'])) 
        $id = intval(mysql_real_escape_string(trim($_POST['id'])));
    } else {
       die("Try not to mess around bro!");
    }

    echo "id=".$_POST['id'];
    $query = mysql_query("SELECT id FROM members WHERE id=$id");
    echo "rows="mysql_num_rows($query);

    if (!$query) {
        die('Query failed to execute for some reason');
    }
    if (mysql_num_rows($query) > 0) {
      echo "this user already exists in the database!";
    }

用上面的代码替换你的代码查询(从$ idp>中删除引用)

答案 1 :(得分:0)

echo "this user already exists in the database!";更改为die("this user already exists in the database!"); 它对我来说非常好用

答案 2 :(得分:0)

这是因为:(缺少开口支撑)。因此,您的POST变量未被传递。

if (isset($_POST['id'])) {
//                       ^-- missing brace
    $id = mysql_real_escape_string(trim($_POST['id']));
} else {
    die("Try not to mess around bro!");
}

请参阅评论// <- to match this brace

if (isset($_POST['id'])) {
//                       ^-- missing brace
    $id = mysql_real_escape_string(trim($_POST['id']));
} // <- to match this brace 
else {
    die("Try not to mess around bro!");
}

答案 3 :(得分:0)

//first you should enable error_Reporting to trace the bug in your code
error_reporting(E_ALL);
//second you should print mysql_error if query fail

//your code should be
$id = 0;//intail value for id so that no error happens if no POST sent
if (isset($_POST['id'])) {
$id = mysql_real_escape_string(trim($_POST['id']));
} else {
  die("Try not to mess around bro!");
}
$query = mysql_query("SELECT id FROM members WHERE id='$id'"); 
if (!$query) {
   die(mysql_error());//to see the error in your query
   //die('Query failed to execute for some reason');
}
if (mysql_num_rows($query) > 0) {
  echo "this user already exists in the database!";
}