views:

1324

answers:

4

Is there anything returned from MySQL/PHP on a INSERT query being executed? Here is my function which I have in a CLASS.

function mysqlQuery($query) {
   // Gets the results from the query
   $results = mysql_query($query, $this->connection);

   // Loops through the queried results as an multi-dimensional array
   while($rows = mysql_fetch_array($results, MYSQL_ASSOC)) {
      // Push results to single array
      $rs[] = $rows;
   }

   // Return results as array
   return $rs;
}

This is how I call the function

$rs = $dbh->mysqlQuery($query);

But executing a INSERT query the $rs returns nothing. Does my function need help or is this the default behavior? Any tips would be helpful as well.

DUH, thanks for reminding me that it returns TRUE/FALSE. for some reason I had it in my head it actually returned another value, but after looking at my function I see I'm not checking for the TRUE/FALSE condition and only looping through the results array.

Thanks for all the correct answers but first to answer correctly got the points, cheers!

+2  A: 

INSERT just returns true or false. to actually return something useful, you will need a SELECT or similar query. there is no result to fetch with INSERT.

contagious
first to answer, thnx
Phill Pafford
+1  A: 

From the php documentation:

Return Values 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.

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.

Ricardo
A: 

From php.net http://us2.php.net/mysql_query

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.

A: 

Generally, when devs are building home functions to manipulates queries, they use two methods. One, "query", used for SELECTs and co, and one, "exec", other INSERTs, UPDATEs and others (like in PDO extension).

If you want to keep your function, add a IF statement around the loop checking the type of $results (with a is_resource() for example)

swordofpain