I'm getting some unusual behavior when using PHP/PDO and doing an INSERT. Here is some sample code:
foreach ($all_users as $this_user) {
try {
$stmt = $db->prepare('INSERT INTO fav_colors (name, color, whattime) VALUES (:name, :color, :whattime)');
$stmt->bindValue(':name', $this_user[name]);
$stmt->bindValue(':color', $this_user[color]);
$stmt->bindValue(':whattime', $this_user[time]);
$stmt->execute();
$count = $stmt->rowCount();
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
if ($count == 1) {
echo "Successful write to table";
} elseif ($count == 0) {
echo "ERROR writing row to table";
}
}
Lets say I have 10 names/colors to insert and the times are DATETIME format (2016-01-01 12:00:00). I have a loop around this code and after the code I check $count to see if the insert worked OK.
Here is my problem. One of the 10 inserts, for whatever reason the $write_time was blank. mySQL generated an error (can't be null). My custom function catchMySQLerror writes the error to a table and e-mails me. It did, but $count was still 1 for this entry and according to it, everything was fine even though the record did not insert.
So is my problem with the try/catch I am using here to catch the exception? How can I add something where I can better handle the error within the code? I know I can add more lines after the catchMySQLerror line and work with the error that way. That is what I have done. But I would like to handle the error using an if/else and with the approach I just mentioned, I can only handle the error... not if it was success.
UPDATE: I edited the code to show how I have been using $count