更新:没有错误,如果条目不存在

时间:2013-04-22 06:58:03

标签: php sql

我只是想知道:如果一个条目不存在,“UPDATE”也会进行“更新”? 我使用以下代码,if语句总是“成功”,特别是当“WHERE”找不到电子邮件时。如果表格中有电子邮件,我是否必须检查?

$email=...;
if ($update_stmt = $mysqli->prepare("UPDATE members SET password = ?, salt = ? WHERE email='".$email."'"))
         {
         $update_stmt->bind_param('ss', $password, $random_salt);

         $update_stmt->execute()
         header("Location: ...?success=1");
         }
         else
            header("Location: ...?error=1");

感谢您的任何建议。

3 个答案:

答案 0 :(得分:1)

这是因为如果匹配存在,您重定向

$update_stmt->execute()
if($update_stmt->affected_rows != 0)
{
    header("Location: ...?success=1");
}
else
{   
    header("Location: ...?error=1");
}

还会在查询之前删除if,因此最终代码看起来像

$update_stmt = $mysqli->prepare("UPDATE members SET password = ?, salt = ? WHERE email='".$email."'"))
$update_stmt->bind_param('ss', $password, $random_salt);
$update_stmt->execute()
if($update_stmt->affected_rows != 0)
{
    header("Location: ...?success=1");
}
else
{   
    header("Location: ...?error=1");
}

答案 1 :(得分:0)

您需要检索受上一个操作影响的行数。这由affected_rows提供。

if ($mysqli->affected_rows == 1)
{
   echo 'A record was deleted';
}

答案 2 :(得分:0)

$email=...;
$mysqli->prepare("UPDATE members SET password = ?, salt = ? WHERE email='".$email."'"))
$update_stmt->bind_param('ss', $password, $random_salt);
$update_stmt->execute();

if ($update_stmt->affected_rows > 0){
   header("Location: ...?success=1");
         }
else
   header("Location: ...?error=1");