I have this big function that gets a lot of different data and insert it into multiple tables.. Not all the data is always available so not all the SQL INSERT queries are successful. I need to check which SQL INSERT query was fully successful and which wasn't to the do something with this data (like inserting into a log table or similar).
Just to give you an example of how I think it can be done:
$sql = 'INSERT INTO data_table (ID, column1, column2) VALUES(?, ?, ?)';
if ($stmt->prepare($sql)) {
$stmt->bind_param('iss', $varID, $var1, $var2);
if ($stmt->execute()) {
$success == TRUE; //or something like that
}
}
I'm not completely sure this is the best way and if its always really show if the data was inserted into the table... Any suggestions??
You can check the @@ROWCOUNT right after insert. If it's more than 0, then the insert succeeded. Also, if @@ERROR = 0 after insert, it was successful. No, check it in T-SQL although if the insert will result in error, most likely the error will be propagated into the client.
For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN , mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return true .
Use if(mysqli_affected_rows($mysqli) >0 ) or no comparison at all. Sidenote: ==1 is only comparing for 1, as opposed to >0 which you may be trying to update more than one row. However and on the rare occasion, >0 is required where this has also happened to me before; that is the reason of my answer.
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.
From the PHP Manual on mysqli_stmt::execute
:
mysqli_stmt::execute
--mysqli_stmt_execute
— Executes a prepared QueryReturns TRUE on success or FALSE on failure.
if ($stmt->execute()) { // exactly like this!
$success = true;
}
You're doing it right... What's your dilemma?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With