Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi PHP: Check if SQL INSERT query was fully successful using MySQLi

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??

like image 265
Jonathan Avatar asked May 20 '10 07:05

Jonathan


People also ask

How do I know if SQL INSERT query was successful?

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.

How can I tell if MySQLi query was successful in PHP?

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 .

How check MySQL update query was successful in PHP?

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.

How can we check INSERT is successful in SQL 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.


1 Answers

From the PHP Manual on mysqli_stmt::execute:

mysqli_stmt::execute -- mysqli_stmt_executeExecutes a prepared Query

Returns TRUE on success or FALSE on failure.


if ($stmt->execute()) { // exactly like this!
    $success = true;
}

You're doing it right... What's your dilemma?

like image 123
Alix Axel Avatar answered Oct 06 '22 01:10

Alix Axel