mySQL no result to show different code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jasemhi
Forum Newbie
Posts: 13
Joined: Sun Aug 29, 2004 10:31 pm

mySQL no result to show different code

Post by jasemhi »

Hi all,

I have a MySQL query that works well, unless there is no result found and then the PHP code doesn't render correctly. The code between the -- while ($row = mysql_fetch_array($result)) { ... } (lines 10 - 23) -- doesn't render and the closing div then is missing and ruins the layout of the page. Can I create an if() that will show a generic table when the MySQL query returns no results? How would this be done?

Code: Select all

$result = mysql_query("SELECT * FROM `table` WHERE `1` LIKE '$search' OR `2` LIKE '$search' OR `3` LIKE '$search' LIMIT 0, 1");
 
echo "<p>Your search for <strong>".$search."</strong> returned the following results:</p>";
 
echo '<div id="table">
<table width="400" border="0">';
 
while($row = mysql_fetch_array($result))
  {
    echo '<tr>';
    echo '<th>1</th>';
    echo '<th>2</th>';
    echo '<th>3</th>';
    echo '</tr>';
    echo '<tr align="center">';
    echo '<td>' . $row['1'] . '</td>';
    echo '<td>' . $row['2'] . '</td>';
    echo '<td>' . $row['3'] . '</td>';
    echo '</tr>';
    echo '<tr>';
    echo '<td colspan="3" align="center"><img src="resources/' . $row['4'] . '" width="200" height="200" alt="image" /></td>';
    echo '</tr>';
    echo "</table></div><p>&nbsp;</p>";
  }
Thank in advance!
iamngk
Forum Commoner
Posts: 50
Joined: Mon Jun 29, 2009 2:20 am

Re: mySQL no result to show different code

Post by iamngk »

add the following code in line no 4 (ie, before echo '<div id="table">)

if(mysql_num_rows($result) >0 ) {
and close if after echoing </div>


one more thing i noticed that you are printing close take wrong. it should be out side of while loop.
echo "</table></div><p>&nbsp;</p>"; [ this line should be out of while loop]
jasemhi
Forum Newbie
Posts: 13
Joined: Sun Aug 29, 2004 10:31 pm

Re: mySQL no result to show different code

Post by jasemhi »

Thanks iamngk! I will try that.

Also, thanks for pointing out my while loop was jacked. I didn't notice because I am only currently pulling only one result.

J
jasemhi
Forum Newbie
Posts: 13
Joined: Sun Aug 29, 2004 10:31 pm

Re: mySQL no result to show different code

Post by jasemhi »

Worked it out with the num_rows. Thanks for your help!
Post Reply