How to avoid inserting data twice in MySQL using PHP and mysqli
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(N开发者_如何学运维ULL, 'Unix Event', '2010-08-24 12:00:00')";
$mysqli->query($query_storeReturnedData);
if(!$mysqli->query($query_storeReturnedData))
{
printf("Errormessage: %s\n", mysqli_error($mysqli));
}
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));
}
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));
}
精彩评论