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

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

if ($stmt->execute()) { 
   // it worked
} else {
   // it didn't
}

Update: since 2022 and beyond, a failed query will throw an error Exception. So you won’t have to write any code to “skip other pieces of code further down the page” – it will be skipped automatically. Therefore you shouldn’t add any conditions and just write the code right away:

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

If you need to do something in case of success, then just do it right away, like

echo "success";

You will see it only if the query was successful. Otherwise it will be the error message.

Leave a Comment