Jump to content

[SOLVED] Is this bad coding practice...


esscher

Recommended Posts

I have a query that does not always bring up a result, and thus echoes this:

 

Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in C:\wamp\www\phytobase\p2\try3.php on line 35

 

Is it bad coding to have this happen, even if I turn off "display errors" in php.ini?

 

Scott

Link to comment
Share on other sites

The error means your query failed for some reason. This not the same as a query that worked but matched zero rows.

 

The error is probably due to a syntax error in the query if you are building it dynamically using form data but the data was not as expected.

 

You always need to check if the mysql_query() returned a false value (query failed) before attempting to access the result resource.

Link to comment
Share on other sites

You always need to check if the mysql_query() returned a false value (query failed) before attempting to access the result resource.

 

Just alaberating on this a bit. Its something newcomers do all the time, not checking returned values. I always see...

 

<?php

  $result = mysql_query("SELECT * FROM foo");
  while ($row = mysql_fetch_assoc($result)) {
    // do something with data.
  }

?>

 

This is terrible. At minimum, to get the same job done use something like...

 

<?php

  $sql = "SELECT * FROM foo";
  if ($result = mysql_query($sql)) {
    if (mysql_num_rows($result)) {
      while ($row = mysql_fetch_assoc($result)) {
        // do something with data.
      }
    } else {
      // no records returned.
    }
  } else {
    // query failed, handle error
    // you can even use the $sql variable here to debug your query
    // you also have access to the mysql_error() function for debugging.
  }

?>

 

Link to comment
Share on other sites

@thorpe,

 

Nice to see you associating the query with a variable. It is a pet peeve of mine to see people put the actual text of the query within the mysql_query() function and then post questions as to why their query is not working. If they were to assign the query to a variable they could simply write it to the screen to see what the error is.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.