Chathurika Chathurika - 6 months ago 10
SQL Question

Check whether a MYSQL Query is null

I want to make if condition according to whether a query is null or not and print two different tables. following is my code.

$number_of_date= "SELECT SUM(number_of_date) AS number_of_date
FROM emp_leaves
WHERE emp_id='$userID'
AND leave_category='Annual'
AND apply_year='$year'";
$number_date = mysql_query ($number_of_date);

if (($number_date == 'NULL'))
{

$result2 = "SELECT * FROM leave_info
WHERE employment_type='permanent'
AND leave_type='annual'";
$sql2 = mysql_query ($result2);

while($row = mysql_fetch_array($sql2)) {
?>
<tr>
<td><?php echo $row["leave_type"]?></td>
<td><?php echo $row["leave_count"]?></td>
</td></tr><?php }
}
else
{
$sql = "SELECT * FROM emp_leaves
WHERE emp_id='$userID'
AND leave_category='Annual'
ORDER BY leave_id DESC limit 1";
$result = mysql_query ($sql);

while($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row["leave_category"]?></td>
<?php }?><?php
while($row11 = mysql_fetch_array($number_date)) {
?>
<td><?php echo $row11["number_of_date"]?></td><?php } } ?>
</tr>


But, "If" condition is not work. What is the correct way of make that condition. Anyone please help me!

Answer

try,

    $number_of_date= "SELECT SUM(number_of_date) AS number_of_date
                      FROM   emp_leaves
                      WHERE  emp_id='$userID' AND
                             leave_category='Annual' AND
                             apply_year='$year'";

    $res_qry     = mysql_query($number_of_date) 
                  or 
                  die ('Invalid query :: <br/>'.$number_of_date.
                                       ' <br/>'.mysql_error());

    $rowqry      = mysql_fetch_assoc($res_qry);
    $number_date = $rowqry ['number_of_date'];

now use, $number_date

    if (($number_date == '') || empty($number_date))

if the query returns NULL, normally PHP considers it as a empty..

you can also try is_null()

Please be informed that mysql functions are deprecated and not recommended. USE MySQLi or PDO instead. have a reference from following queries.

http://php.net/manual/en/book.mysqli.php

http://php.net/manual/en/book.pdo.php

Comments