views:

29

answers:

2

I have the following code:

<table>
<thead>
  <tr>
    <th>Service</th>
    <th>Status</th>
  </tr>
</thead>
<?php $result = mysql_query("SELECT Service, Status FROM services WHERE Company='Company 1'");
  while ($row = mysql_fetch_array($result)) {
          //  ^ must be a single '=' !!!!
      echo '<tr><td>' . $row["Service"] . '</td>';
      echo '<td>' . $row["Status"] . '</td></tr>';
  } ?>
</table>

To display multiple rows from a MySQL database in an HTML table. My question is.. how would I determine if there are no rows that match my criteria, and display a message indicating that it is empty?

+1  A: 

In my opinion, the best way is a if statement + do/while loop :

$result = mysql_query("your query");

if ($row = mysql_fetch_array($result)) {
    do {
        // your loop stuff
    } while ($row = mysql_fetch_array($result));
} else {
    echo "No result";
}

You can also use mysql_num_rows function, but keep in mind there is no such function for PDO API and the do/while solution works with any API.

P.S. If you only use the associative part of your array, use mysql_fetch_assoc instead of mysql_fetch_array.

Vincent Savard
omg, I always used mysql_num_rows but this code is much cleaner! +1
Time Machine
I'd really like to know why my post was downvoted, this is always the solution I use with PDO and if someone knows better, I'd like to know as well!
Vincent Savard
Great code! Thanks!
Zachary Brown
+2  A: 

You could use the mysql_num_rows() function:

$result = mysql_query("SELECT Service ... ");

if (mysql_num_rows($result) > 0) {
   // Display Results
}
else {
   // No Results
}
Daniel Vassallo
Or even `if (mysql_num_rows($result))` (it returns `FALSE` on fail as well)
amphetamachine