Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL INSERT return value with one query execution

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.

like image 403
Phill Pafford Avatar asked Sep 28 '09 17:09

Phill Pafford


People also ask

What does insert query return in PHP?

6 Answers. Show activity on this post. INSERT just returns true or false. to actually return something useful, you will need a SELECT or similar query.

Can we insert single or multiple records using a single query in MySQL?

INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.

What does the insert () function return?

Returns the original string with specified text inserted at a specific byte location.

Can you insert multiple values in MySQL?

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of comma-separated column values, with lists enclosed within parentheses and separated by commas.


2 Answers

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.

like image 182
helloandre Avatar answered Oct 07 '22 21:10

helloandre


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.

like image 23
Ricardo Avatar answered Oct 07 '22 19:10

Ricardo