Matt Bryce
Matt Bryce

Reputation: 123

php echo if query is empty

I'm querying a database but when the result is empty i want to output a table row displaying "nothing to display" but the if seems to always return true.

Here's my code...

$priorityincidentsQ         = mysql_query("SELECT * FROM applications WHERE pi >= ('2') ");
while($priorityincidentsR   = mysql_fetch_object($priorityincidentsQ)) 
  {
    if (empty($priorityincidentsR)) {
      echo "<tr><td class=\"closedcallscell centered\"><b>Nothing to display</b></td></tr>";    
    } else {        
      echo "<tr><td class=\"closedcallscell\"><b>$priorityincidentsR->application_friendly_name</b></td>";
      echo "<td  class=\"closedcallscell table_row_small\"><center>$priorityincidentsR->pi</center></td></tr>"; 
    }
  }

Upvotes: 2

Views: 4644

Answers (2)

Matt Bryce
Matt Bryce

Reputation: 123

Still never figured out why this wouldn't work out for me this way, I tried the query directly in SQL workbench and everything looks how it should, I ended up solving the problem like this.

<!-- priority incidents-->
<?php

$priorityincidentsQ         = mysql_query("SELECT * FROM applications WHERE pi >= ('1') ");
while($priorityincidentsR   = mysql_fetch_object($priorityincidentsQ)) 
    {
    echo "<tr><td class=\"closedcallscell\"><b><a href=\"".DIR."?p=$priorityincidentsR->pageID\">$priorityincidentsR->application_friendly_name</a></b></td>";
    echo "<td  class=\"closedcallscell table_row_small\"><center>$priorityincidentsR->pi</center></td></tr>";
    }

?>

<!-- if no incidents-->
<?php

$incidentNumberofRowsQ      = mysql_query("SELECT COUNT(*)numberofrows FROM applications WHERE pi >= ('1') ");
while($incidentNumberofRowsR    = mysql_fetch_object($incidentNumberofRowsQ)) 
    {

        if ($incidentNumberofRowsR->numberofrows == '0')
        {
                echo "<tr><td class=\"closedcallscell centered\"><b>Currently no priority incidents</b></td>";
        }
    }

?>

may seem a rather silly way of going about it but atleast it works. Thanks all for the help. :)

Upvotes: 0

mitkosoft
mitkosoft

Reputation: 5316

Use mysqli_num_rows() to check is there any result:

    $conn = mysqli_connect($host, $user, $password, $database);
    $priorityincidentsQ = mysqli_query($conn, "SELECT * FROM applications WHERE pi >= ('2') ");
    if (mysqli_num_rows($priorityincidentsQ) > 0){
        while ($priorityincidentsR = mysqli_fetch_object($priorityincidentsQ)) {
            echo "<tr><td class=\"closedcallscell\"><b>$priorityincidentsR->application_friendly_name</b></td>";
            echo "<td  class=\"closedcallscell table_row_small\"><center>$priorityincidentsR->pi</center></td></tr>";
        }
    }else{    
        echo "<tr><td class=\"closedcallscell centered\"><b>Nothing to display</b></td></tr>";
    }

And yes, better use mysqli_* functions instead of mysql_*.

Upvotes: 4

Related Questions