473,503 Members | 1,731 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Atli
5,058 Recognized Expert Expert
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 5588

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

Similar topics

4
7822
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
16896
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
2690
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
3573
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
2347
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
5018
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
2242
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
4715
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
2187
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
3223
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
7203
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
7334
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...
1
6993
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
7462
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...
1
5014
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1514
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
737
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
383
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.