php不返​​回消息:如果recod不存在,则“记录不存在”

时间:2019-07-09 18:17:29

标签: php mysql

我创建了一个表单,如果ID为“ Telefoni_number”,则该表将更新表“ Komentaar”。但是,即使我输入了不存在的ID,我仍然会收到回显“记录成功更新”。

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "client.id");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Attempt update query execution
$sql = "UPDATE clientid SET Komentaar='OK' WHERE          
    Tele foni_number=5207245";

if(mysqli_query($link, $sql)){
    echo "Records were updated successfully.";
} else  {
    echo "ERROR: Could not able to execute $sql. " .             mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>

2 个答案:

答案 0 :(得分:1)

您正在打印Records were updated successfully,以查看是否执行了查询。当然,查询已执行,无论是否进行了任何更改。您必须使用if any rows were affected解决mysqli_affected_rows()的情况。

$sql = "UPDATE clientid SET Komentaar='OK' WHERE Telefoni_number=5207245";
$result = mysqli_query($link, $sql);
if(if (mysqli_affected_rows($link)){
    echo "Records were updated successfully.";
} else  {
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

答案 1 :(得分:0)

发生这种情况的原因是该函数的返回值:

mysqli_query($link, $sql)

只要您提供有效的SQL语法,就总是正确的。您已经成功用该电话号码更新了每一行,顺便说一句,它恰好为零。要确定您的代码是否确实影响了任何行,可以使用mysqli_affected_rows。请参阅文档:

https://www.php.net/manual/en/mysqli.affected-rows.php

所以您的代码可能类似于:

if(mysqli_query($link, $sql)){
    if(mysqli_affected_rows($link)) {
        echo "Records were updated successfully.";
    } else {
        echo  "ERROR: No records were found!";   
    }
} else  {
    echo "ERROR: Could not able to execute $sql. " .             mysqli_error($link);
}