PHP:如何检查数据库中的 ID 是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7286966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: How to check if ID in database exists
提问by Kaizokupuffball
Why won't this send the user to user.php if the ID don't exist in the table?
如果 ID 不存在于表中,为什么不将用户发送到 user.php?
<?php
include 'db_connect.php';
$id_exists = false;
$url_id = mysql_real_escape_string($_GET['id']);
$sql = "SELECT id FROM members WHERE id='$url_id'";
$result = mysql_query($sql);
if ($result == $url_id)
{
$id_exists = true;
}
else if ($result != $url_id)
{
$id_exists = false;
header("location:user.php");
exit();
}
?>
Thx in advance!
提前谢谢!
回答by MrE
$url_id = mysql_real_escape_string($_GET['id']);
$sql = "SELECT id FROM members WHERE id='$url_id'";
$result = mysql_query($sql);
if(mysql_num_rows($result) >0){
//found
}else{
//not found
}
Try something like this :). http://php.net/manual/en/function.mysql-num-rows.php
尝试这样的事情:)。 http://php.net/manual/en/function.mysql-num-rows.php
回答by mfonda
Please, read the docs for mysql_query
. You have to fetch the result after making the query. That said, you should probably use PDOinstead of mysql_*
.
请阅读mysql_query
. 您必须在进行查询后获取结果。也就是说,您可能应该使用PDO而不是mysql_*
.
回答by Allain Lalonde
Because mysql_query doesn't return a row, it returns a resource.
因为 mysql_query 不返回一行,它返回一个资源。
Use mysql_num_rows($result)
to check if there is a row returned.
使用mysql_num_rows($result)
以检查是否有返回的行。