tags:

views:

18

answers:

2

Forgive me if this is a particularly stupid question!

mysql_query($query)

returns a boolean, but you can also assign it to a variable

$results = mysql_query($query)

and then use the other mysql_ functions to extract data.

Out of curiosity, how does mysq_query($query) act as both a boolean and a data container at the same time? What's happening "under the hood" during these steps?

(yes, I am a n00b..., please be kind!)

+4  A: 

If you notice, when it returns true/false, you can't use it with the other functions such as mysql_fetch_assoc().

From the mysql_query() documentation:

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.or FALSE on error.

What happens, is for statements that do not return data, it responds true/false on whether or not the query was successful.

When there is a result set, you will see it returns a MySQL resource. This is a special value that allows PHP to figure out what data set you are talking about. You then pass this resource to other MySQL function to retrieve the data.

See: http://www.php.net/manual/en/language.types.resource.php

Chacha102
It's important to clarify that an object with at least one member variable or an array with at least one element is considered TRUE. Otherwise it's considered FALSE.
Ben
Yes, as Ben mentioned, at least in the case of `if` statements, something can be considered `true` but still not be a boolean.
Chacha102
Thank you for taking the time to explain that, Chacha. :-)
Andrew Heath
A: 

Doing

var_dump(mysql_query($query));

should tell you it's a resource (as well as its id)

alex