MySqli UPDATE, detect if entry doesn't exist

时间:2016-04-04 18:41:03

标签: php mysql mysqli

I am updating the DB when I receive some data from an API I'm using.

And I changed value to something that is not in my DB, while I'm testing to see if it will give off an error. It did not, everything went on as if the var was a match and the DB was updated.

What would be a way to check for this?

foreach($message_id_array as $key=>$value) {

$query = "UPDATE `sms_messages_tbl` 
SET `delivery2_api_to_enduser`= '1',
`delivery2_response_time` = UTC_TIMESTAMP(),
`delivery2_response_api_ip`= '".$ip."',
`delivery2_response_from_api`= '".$message_status_array[$key]."'
WHERE `transaction_sms_id` = '".$value."' ";


if ($conn->query($query) === TRUE) {                                                    
     echo ''.$message_status_array[$key].':'.$value.':OK';                                                      
} else {
     echo "Error updating record: " . $conn->error;
}                                       
$conn->close();                                                         
}

2 个答案:

答案 0 :(得分:1)

There is no error returned because MySQL does not return any errors on UPDATE ( except the syntax schema-related ones of course ).

You can go into phpMyAdmin because I guess you're using it, and run the same update with some dummy values, you'll see the result is a success with 0 affected rows.

The update still happened successfully and it affected no rows because none met the requirements.

Just so you can get a clearer idea of what happened, you can look for the number of affected rows using the following:

if ($conn->query($query) === TRUE) {
    echo ''.$message_status_array[$key].':'.$value.':OK';
    echo $conn->affected_rows . ' affected';
}

It will say the update was fine and the number of affected rows is 0.

答案 1 :(得分:0)

我建议对数据库的选择请求“Select * FROM table WHERE'id'= $ value”。

然后运行mysqli_num_rows。如果结果!= 0,请执行SET查询。

相关问题