Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$stmt->execute() : How to know if db insert was successful?

Tags:

oop

php

mysqli

With the following piece of code, how do i know that anything was inserted in to the db?

if ($stmt = $connection->prepare("insert into table (blah) values (?)")) { $stmt->bind_param("s", $blah);   $stmt->execute();            $stmt->close();                                  } 

I had thought adding the following line would have worked but apparently not.

if($stmt->affected_rows==-1){$updateAdded="N"; echo "failed";}   

And then use the $updatedAdded="N" to then skip other pieces of code further down the page that are dependent on the above insert being successful.

Any ideas?

like image 882
cosmicsafari Avatar asked Apr 03 '12 10:04

cosmicsafari


People also ask

How can we check insert query was successful in PHP?

To check if your INSERT was successful, you can use mysqli_affected_rows() . Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query. And check for errors against your query and for PHP.

What does execute() php return?

execute() - Returns TRUE on success or FALSE on failure.

How check PDO query is successful in PHP?

de.php.net/manual/en/pdostatement.execute.php says: Returns TRUE on success or FALSE on failure. - So bind it to a variable, e.g. $success = $STH->execute($params); and check that variable against true or false .

What STMT execute return?

Statement execute(String query) is used to execute any SQL query and it returns TRUE if the result is an ResultSet such as running Select queries.


2 Answers

The execute() method returns a boolean ... so just do this :

if ($stmt->execute()) {     // it worked } else {    // it didn't } 
like image 111
Manse Avatar answered Oct 03 '22 11:10

Manse


Check the return value of $stmt->execute()

if(!$stmt->execute()) echo $stmt->error; 

Note that line of code does perform the execute() command so use it in place of your current $stmt->execute() not after it.

like image 41
MattP Avatar answered Oct 03 '22 09:10

MattP