如果数据库php中不存在记录,则显示自定义消息


Show custom message if record does not exist in database php

如果数据库中不存在记录,是否可以显示自定义错误消息?

例如,此页面在数据库中作为记录存在:

testpage.php?recordID=123456

而这个记录没有:

testpage.php?recordID=857389

您需要检查使用mysql_num_rows()返回的行数。如果存在记录,mysql_num_rows将返回1或更大的值(与查询匹配的行数)。

您可能还想首先检查查询是否真的运行过,或者它是否在sql中遇到错误。它将详细说明mysql_error()中的错误。

$query = mysql_query($example_sql);
if (!$query = mysql_query($example_sql))
{
    trigger_error(' Mysql_error: ' . mysql_error() . " SQL: " . $example_sql, E_USER_WARNING); //Outputs the error to your error log
    echo "There was an error contacting the database.";
}
else if (mysql_num_rows($query) <= 0)
{
   echo "That record does not exist.";
}
else
{
    //Query returned 1 or more rows, output as normal
}

您需要检查返回了多少带有该记录id:的结果

<?php
$recordID = $_GET['recordID'];
$sqldb = /*create database connection here*/
$result = mysql_query("SELECT * FROM your_table WHERE id = " . $recordID, $sqldb);
$num_rows = mysql_num_rows($result);
if($num_rows > 0)
{
  echo "record exists with id " . $recordID;
}else
{
  echo "record doesn't exist with id " . $recordID;
}
?>

如果数据库中不存在记录,是否可以显示自定义错误消息?

是的。

通常,接收这样的变量的页面由查询数据库的代码组成。并得到一些结果。

不禁止使用条件运算符检查这样的结果并显示任何消息(很可能是HTTP 404响应)。

您可以对行mysql_num_rows进行计数,这样可以查找ID是否存在,1行=存在,0行=不存在。

if (mysql_num_rows($query) < 1) {
    print "This record does not exist);
}