Dinusha Rathnaweera Dinusha Rathnaweera - 6 months ago 11
SQL Question

checking emptiness of the fetch array

include("connect.php");

$SQL="SELECT * FROM promo ";
$run=mysql_query($SQL,$con) or die ("SQL error");
$rec=mysql_fetch_array($run);


first,I want to check whether this query is giving empty records or not.
If it doesn't output any records , should print " no records in the table"
otherwise print all records using while loop.
I can show the records using while loop. the hard thing is checking the output is empty or not.

please help me to do this. Thank you

echo "<table border='1' align='center' >";
echo "<tr> <th> Room ID </th> <th> Start Date </th> <th> End Date </th> <th> Promo Rate </th> </TR>";

$run=mysql_query($SQL2,$con) or die ("SQL2 error");
while($rec2=mysql_fetch_array($run))
{
echo "<tr>";
echo "<td>".$rec2['roomid']."</td>";
echo "<td>".$rec2['startdate']."</td>";
echo "<td>".$rec2['enddate']."</td>";
echo "<td>".$rec2['rate']."</td>";
echo "</tr>";
}

echo "</table>";

Answer

Despite you're using an obsolete API which is deprecated and in php7 even removed, the solution is to check number of rows returned by a query with mysql_num_rows:

$SQL="SELECT * FROM promo ";
$run = mysql_query($SQL,$con) or die ("SQL error");
if (0 < mysql_num_rows($run)) {
    while($rec2=mysql_fetch_array($run))
        // echo your rows
    }
} else {
    echo 'No rows found.';
}

But in the end - consider moving to more up-to-date APIs - mysqli or PDO.

Comments