tags:

views:

33

answers:

2

I'm trying to catch error messages returned from a mysql server on insert failure. The below method works fine when fetching data, but on insert, the 'if' statement below inserts the data a second time. How can I re-write this to catch error messages without inserting the data again.

    $mysqli = new mysqli("localhost", "user", "pass", "database");

    $query_storeReturnedData = "INSERT INTO `eventStore` (table_key, event_type, event_date,) VALUES(NULL, 'Unix Event', '2010-08-24 12:00:00')";

    $mysqli->query($query_storeReturnedData);

    if(!$mysqli->query($query_storeReturnedData))
    {
     printf("Errormessage: %s\n", mysqli_error($mysqli));
    }
+1  A: 

Because you have two calls to $mysqli->query you are seeing double insertions.

You can remove the first call to $mysqli->query

// no need of this.
// $mysqli->query($query_storeReturnedData);

// make just one call and also do err checking.
if(!$mysqli->query($query_storeReturnedData)) {
   printf("Errormessage: %s\n", mysqli_error($mysqli));
}

Alternatively you can collect the return value of $mysqli->query and use it in error checking:

// run the query and collect the return value.
$return_value = $mysqli->query($query_storeReturnedData);

// if return value is false..query failed...print err msg.
if(!$return_value)) {
   printf("Errormessage: %s\n", mysqli_error($mysqli));
}
codaddict
Your alternate solution explains it. Should have been evaluating against the return value not the function call. Going to store this under 'duh!'. Thanks
JMC
+2  A: 

How about this?

$mysqli = new mysqli("localhost", "user", "pass", "database");

$query_storeReturnedData = "INSERT INTO `eventStore` (table_key, event_type, event_date,) VALUES(NULL, 'Unix Event', '2010-08-24 12:00:00')";

if(!$mysqli->query($query_storeReturnedData))
{
 printf("Errormessage: %s\n", mysqli_error($mysqli));
}
WoLpH