【问题标题】:How to check if ID in database exists如何检查数据库中的ID是否存在
【发布时间】:2011-09-02 17:13:26
【问题描述】:

如果表中不存在 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();
}
 
?> 

【问题讨论】:

  • 通常会使用调试来找出答案。另请查看手册以了解 mysql_query() 返回的值

标签: php mysql get


【解决方案1】:
$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
}

试试这样的:)。 http://php.net/manual/en/function.mysql-num-rows.php

【讨论】:

  • 谢谢!我也会看看 num-rows 函数。
【解决方案2】:

请阅读mysql_query 的文档。您必须在进行查询后获取结果。也就是说,您可能应该使用PDO 而不是mysql_*

【讨论】:

    【解决方案3】:

    因为 mysql_query 不返回一行,它返回一个资源。

    使用mysql_num_rows($result) 检查是否有返回行。

    【讨论】:

    • 对于 SELECT、SHOW、DESCRIBE、EXPLAIN 和其他返回结果集的语句,mysql_query() 成功时返回资源,错误时返回 FALSE。
    • @Pramendra:返回零行的查询仍然成功,因此将返回没有行的资源,而不是 FALSE。
    猜你喜欢
    • 2010-10-22
    • 2012-01-09
    • 2021-12-11
    • 2013-08-22
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多