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
https://forums.phpfreaks.com/topic/89758-solved-is-this-bad-coding-practice/
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.

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.
  }

?>

 

@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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.