Page 1 of 1

mySQL no result to show different code

Posted: Wed Jul 29, 2009 8:21 pm
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!

Re: mySQL no result to show different code

Posted: Wed Jul 29, 2009 11:15 pm
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]

Re: mySQL no result to show different code

Posted: Thu Jul 30, 2009 7:46 pm
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

Re: mySQL no result to show different code

Posted: Sat Aug 01, 2009 6:57 am
by jasemhi
Worked it out with the num_rows. Thanks for your help!