Ton*_* Xu 3 php sql insert-update
我使用这段php插入/更新mysql db。请在相应行的注释部分中查看我的问题。谢谢。
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);
arr = array();
if (strcasecmp($actionIn, 'insert') == 0) {
$query = "INSERT INTO $usertable (id, fname, lname) VALUES ('$id', '$fname', 'lname'";
$result = mysql_query($query) or die(mysql_error()); //AT THIS STEP, I would get error message if I insert a duplicated id into table, no following json_encode would not print out, that's what I want.
if ($result) {
$arr['inserted'] = 'true';
}
exit(json_encode($arr));
}
if (strcasecmp($actionIn, 'update') == 0) {
$query = "UPDATE $usertable SET id = '$id', fname = '$fname', lname = '$lname' WHERE id = '$id'";
$result = mysql_query($query) or die(mysql_error()); //AT THIS STEP, if I update a non-existent id, I don't get error, and the following steps continue to execute. I want the error info or return me a false.
if ($result) {
$arr['updated'] = 'true';
}
exit(json_encode($arr));
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过这些,但是num_rows和受影响的行都返回0。为什么?
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
$aff_cnt = $result->affected_rows;
printf("Result set aff %d rows.\n", $aff_cnt);
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
小智 5
如果UPDATE不匹配任何更新,它将简单地返回。这不是错误。要查找是否已更新,请使用mysql_affected_rows()。
注意:mysql_*()不支持OOP表单,因此您应该使用mysql_affected_rows(),它应该可以在上述第二种情况下使用。
这将为您提供:
if (strcasecmp($actionIn, 'update') == 0) {
$query = "UPDATE $usertable SET id = '$id', fname = '$fname', lname = '$lname' WHERE id = '$id'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows() !== 0) {
$arr['updated'] = 'true';
}
Run Code Online (Sandbox Code Playgroud)
旁注:mysql_*()已弃用,将被移除。您应该将mysqli或PDO用于新代码。