Search code examples
phpmysqldie

Die if Data Not Exisits in php mysql table


I'm getting an error message when the data is not available in data base table. I would like to stop the qry search without getting an error when the data is not available. It works good if the data is available in table but not works while the data is not available. For an example, when i search this city name in my table the requested city's data's are not available in that table. During this time i'm getting an "Undefined variable" error.

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

?>

Solution

  • Please try Below Code (Not Tested Yet) :

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