如果php mysql表

时间:2017-03-13 08:36:07

标签: php mysql die

当数据在数据库表中不可用时,我收到错误消息。我希望在数据不可用时停止qry搜索而不会出现错误。 如果数据在表中可用但在数据不可用时不起作用,则效果很好。例如,当我在表格中搜索此城市名称时,该表格中没有所请求城市的数据。在此期间我收到“未定义变量”错误。

<?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'];
}

?>

2 个答案:

答案 0 :(得分:1)

检查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'];
    }
}

答案 1 :(得分:0)

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

<?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";
}
?>