473,396 Members | 2,018 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,396 developers and data experts.

PHP - Common Newbie Pitfalls, 2: Supplied argument is not a valid MySQL result

Atli
5,058 Expert 4TB
What to discuss:
  • What is a "MySQL resource".
  • What causes the error.
  • How to fix it.

Common Newbie Pitfalls
This article is the second installment in a series of (hopefully) many, following Markus' first installment: 1: Headers Already Sent.

Written by the PHP experts at bytes.com, these articles hope to cover those common bear traps often encountered — and subsequently asked on the bytes.com forums — by PHP newcomers in a clear and concise manner.

Part 2: Supplied argument is not a valid MySQL result

Index:
  1. What is a "MySQL resource"?.
    1. MySQL "link" resource.
    2. MySQL "result" resource.
  2. What causes the error?
  3. How to fix it?


1. What is a MySQL resource?
A resource is a link to an external service or data source. (See PHP: Resources - Manual)
PHP has two main resource types that deal specifically with MySQL: "mysql_link" and "mysql_result".

1.1. MySQL "link" resources
These tell PHP how to communicate with MySQL.

When you call mysql_connect, PHP opens a connection to the MySQL server. If successful, the connection is opened and the connection details are stored in memory. The "mysql_link" resource is a link to the memory location where those details are stored.

1.2. MySQL "result" resources
These point to memory locations where PHP stores the results of a MySQL query.

When you do a mysql_query, MySQL returns all the rows in the result-set to PHP immediately. However, in order to give you the ability to traverse the result set at your own pace, PHP "buffers" the result in memory, storing the exact location of the data in a "mysql_link" resource, along with the position of your code inside the result set.

2. What causes the error?
This warning is shown when we try to pass variables that are not MySQL resources into functions that require them to be MySQL resources, such as the mysql_fetch_row function.

This is always a result of poor error handling. That is; the programmer forgot to write fail-safes in case the function that generates the resource fails. Common causes for that is when you pass invalid database info to the mysql_connect function or pass an invalid SQL query to the mysql_query function. Neither of those functions will cause the errors themselves, but they will return FALSE rather than the MySQL resource they are expected to return, so in the following code, functions that use their return values will not function correctly, and will display this error.

We see a lot of questions about this posted in the PHP forums. Developers that are new to PHP will often do something like this:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // Open a link to a MySQL database.
  3. $my_link_resource = mysql_connect('host', 'usr', 'pwd');
  4. mysql_select_db('db', $my_link_resource);
  5.  
  6. // Execute a query on the open database.
  7. $sql = "SELECT stuff FROM my_table";
  8. $my_result_resource = mysql_query($sql, $my_link_resource);
  9.  
  10. // Loop through the result set, printing each row.
  11. while($row = mysql_fetch_row($my_result_resource)) {
  12.     var_dump($row); // For debug only!
  13. }
  14. ?>
There are 3 lines in that code that may well cause an error, such as the one this article covers:
  1. Line #4. The "mysql_select_db" function is meant to set the active database on an open MySQL connection, using a MySQL link resource to connect to MySQL. If the preceding "mysql_connect" function fails, the "mysql_select_db" function will not know what MySQL server to use, and will therefore fail, giving us an error message.
  2. Line #8. Again, if the "mysql_connect" call on line #3 fails, the "mysql_query" function will not know how to connect to MySQL, and will therefore fail.
  3. Line #11. The "mysql_fetch_row" function relies on the "mysql_query" function to provide it a "mysql_result" resource. If any of the preceding functions: "mysql_connect", "mysql_select_db", or "mysql_query", fail, this function is also likely to fail.


3. How do I fix it?
There is only one thing you need to do to make sure this error doesn't affect you: validate the return value of the "mysql_*" functions.

How you do that is pretty simple: you use if...else statements to check if the return values of those functions are in fact what they are supposed to be. - Consider this rewrite of the example I showed you before.
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // Open a link to a MySQL database.
  3. $my_link_resource = mysql_connect('host', 'usr', 'pwd');
  4. if($my_link_resource === FALSE) {
  5.     echo 'Failed to connect to MySQL: ' . mysql_error();
  6.     exit;
  7. }
  8. if(!mysql_select_db('db', $my_link_resource)) {
  9.     echo 'Failed to select MySQL database: ' . mysql_error();
  10.     exit;
  11. }
  12.  
  13. // Execute a query on the open database.
  14. $sql = "SELECT stuff FROM my_table";
  15. $my_result_resource = mysql_query($sql, $my_link_resource);
  16.  
  17. // Makes sure the query was successful
  18. if($my_result_resource !== FALSE) {
  19.     // Loop through the result set, printing each row.
  20.     while($row = mysql_fetch_row($my_result_resource)) {
  21.         var_dump($row); // For debug only!
  22.     }
  23. }
  24. else {
  25.     echo 'MySQL Query failed.<br>';
  26.     echo ' - Error: ' . mysql_error() . '<br>';
  27.     echo " - Query: {$sql}<br>";
  28.     exit;
  29. }
  30. ?>
This, instead of resulting in the rather useless warning we are discussing, would print out useful error messages you could use to debug and fix the problem.

However, being rather verbose, a lot of developers like to replace the if...else blocks with a simple die call. This makes the code a lot shorter, but in return you lose a bit of the control the if...else blocks give you.
You could rewrite the previous example like so, to incorporate this method:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // Open a link to a MySQL database.
  3. $my_link_resource = mysql_connect('host', 'usr', 'pwd') or die(mysql_error());
  4. mysql_select_db('db', $my_link_resource) or die(mysql_error());
  5.  
  6. // Execute a query on the open database.
  7. $sql = "SELECT stuff FROM my_table";
  8. $my_result_resource = mysql_query($sql, $my_link_resource) or die(mysql_error());
  9.  
  10. // Loop through the result set, printing each row.
  11. while($row = mysql_fetch_row($my_result_resource)) {
  12.     var_dump($row); // For debug only!
  13. }
  14. ?>
But regardless, either method will produce a lot more helpful error messages when your MySQL functions fail.
Feb 12 '10 #1
0 5574

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

Similar topics

4
by: Ryanlawrence1 | last post by:
Heya, I get these 2 errors: Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/themepar/public_html/changepass.php on line 20 You have not entered all the...
2
by: techjohnny | last post by:
Error: Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/jplane/certcent/phpweb/quiz/index.php on line 20 Warning: mysql_num_rows(): supplied argument is...
1
by: lsmamadele | last post by:
I am getting the following error messages in my search: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/mamadele/public_html/BESTPLAYS/search.php on...
11
by: Breana | last post by:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/breana/public_html/category.php on line 88 ------------------------------------------- It does this...
5
by: Mubs | last post by:
Hi, I 'am trying to connect my sql database with my webpage for users log in. i have got this script so far but i keep getting the following error message which i cannot figure out.. could any1...
4
by: fisherd | last post by:
When i run this code, i keep getting this message; Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\wamp\www\checklogin.php on line 26 i use this code to...
4
by: kalyanip14 | last post by:
Hi I am new to Php.I am trying to read My sql database data from table to php. I am getting this warning Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource ...
11
by: chemlight | last post by:
I'm having a problem. I'm sure I'm going to kick myself over the answer... I have a table that stores vendors and their languages. This table starts out blank. I am querying the table to see if a...
2
by: perhapscwk | last post by:
When I run my site from localhost, no error, but when I move it to webhosting, it show below error, why? Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in...
2
by: macdalor | last post by:
Hi! I'm completely new to all dev and trying to put a website together using MySQLI and PHP; was running fine until I try to gather the DB content with the following script: <?...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.