如果 php mysql table 中不存在数据,则死亡

Die if Data Not Exisits in php mysql table

当数据库 table 中的数据不可用时,我收到一条错误消息。当数据不可用时,我想停止 qry 搜索而不会出现错误。 如果数据在 table 中可用,则效果很好,但在数据不可用时不起作用。例如,当我在 table 中搜索这个城市名称时,请求的城市数据在 table 中不可用。在此期间,我遇到 "Undefined variable" 错误。

<?php 
$city = 'chennai';

$cityQry ="SELECT * FROM area_data WHERE city ='$city' LIMIT 1";
$cityQryResult = mysql_query($cityQry);
while($row = mysql_fetch_array($cityQryResult)) {
$citypop = $row['population'];
}

?>

请尝试以下代码(尚未测试):

<?php
$city = 'chennai';
$cityQry ="SELECT * FROM area_data WHERE city ='$city'";
$result = mysqli_query($cityQry);
// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);
if($count > 0)
{
    $cityQryResult = mysql_query($cityQry);
    while($row = mysql_fetch_array($cityQryResult)) {
        $citypop = $row['population'];
    }
} else {
    echo "No Data Exists";
}
?>

检查 mysql_num_rows 给你的计数是否大于 0,如果计数为 0 则调用 die()

$city = 'chennai';
$cityQry ="SELECT * FROM area_data WHERE city ='$city' LIMIT 1";
$cityQryResult = mysql_query($cityQry);
if(mysql_num_rows($cityQryResult) == 0)
{
    die("No Data Exists");
} else {
    while($row = mysql_fetch_array($cityQryResult)) {
         $citypop = $row['population'];
    }
}