1

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));
    }

2 Answers 2

2

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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your alternate solution explains it. Should have been evaluating against the return value not the function call. Going to store this under 'duh!'. Thanks
2

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.