10

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

Salman A
  • 262,204
  • 82
  • 430
  • 521
Jonathan
  • 8,676
  • 20
  • 71
  • 101

2 Answers2

16

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?

Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • Err, no, it should read `$success = TRUE;` since you don't want to test for equality but want to assign a value to the $success variable. – wimvds May 20 '10 at 10:30
4

I believe you can use mysqli_stmt->affected_rows to return the number of rows inserted (or changed or deleted).

Salman A
  • 262,204
  • 82
  • 430
  • 521