html output for a MySQL query without result

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • uranuskid
    New Member
    • Mar 2007
    • 19

    html output for a MySQL query without result

    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("SE LECT 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_arr ay($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_c lose($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.
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    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("SE LECT 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:

    Comment

    • uranuskid
      New Member
      • Mar 2007
      • 19

      #3
      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

      Comment

      • ronverdonk
        Recognized Expert Specialist
        • Jul 2006
        • 4259

        #4
        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:

        Comment

        Working...