By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,359 Members | 1,495 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,359 IT Pros & Developers. It's quick & easy.

html output for a MySQL query without result

uranuskid
P: 19
Hey folks,

Today I'm after a solution for a pretty simple problem, however, too hard for me to solve. I've got a MySQL query that reveals a table output. But if there is no result it is displaiing my table heads instead of the "else" message. The code is as follows, maybe someone could help. Cheers, Frank

[PHP]
$result = mysql_query("SELECT var_01, var_02, var_03, var_04 var_05 FROM table WHERE var_01 = '$_POST[a]' AND var_02 = '$_POST[b]'
AND var_03 = '$_POST[c]'
ORDER BY var_01");

if ($result)
{
echo "<table border='1'>
<tr>
<th>var1</th>
<th>var2</th>
<th>var3</th>
<th>var4</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['var_01'] . "</td>";
echo "<td>" . $row['var_02'] . "</td>";
echo "<td>" . $row['var_03'] . "</td>";
echo "<td>" . $row['var_04'] . "</td>";
echo "</tr>";
}

echo "</table>";mysql_close($con);
}else {

print "<h2>Sorry, no entries available!</h2>";

}

[/PHP]

The script works fine if there is a result. But if there is no result it gives me the table head instead of the error message.
Apr 1 '07 #1
Share this Question
Share on Google+
3 Replies


ronverdonk
Expert 2.5K+
P: 4,258
The $result does not contain row values, but the resource id of the query. By accessing that resource id in a command like mysql_fetch_row you retrieve the result set.

So it is better to check the number of rows and act upon that. (I also suggest that you catch any possible errors in the select statement). Your code would be something like:

[php]
$result = mysql_query("SELECT var_01, var_02, var_03, var_04 var_05 FROM table WHERE var_01 = '$_POST[a]' AND var_02 = '$_POST[b]'
AND var_03 = '$_POST[c]'
ORDER BY var_01")
or die("SELECT error: ".mysql_error()); // catch any error

if (mysql_num_rows($result) > 0) {
echo "<table border='1'>
// .... rest of code .....
[/php]

Ronald :cool:
Apr 1 '07 #2

uranuskid
P: 19
Thanks Ronald,

The little adjustment with mysql_num_rows() function solved the issue. I understand that without it I just query the result as itself that returns a result in any case. Therefoe my else clause would never be true.

Cheers

Frank
Apr 1 '07 #3

ronverdonk
Expert 2.5K+
P: 4,258
As said before, variable $result does not contain any row values, but the resource identifier of the result set. Usually something like 'RESOURCE #1' or alike.

Ronald :cool:
Apr 1 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.