简体   繁体   中英

PHP always reports SQL success even when it fails

This is a simple one, maybe I'm having a long brain fart or something, but whats happening is the form is used to set a record only if the name and their cpukey matches then it will continue, as this is a public page with no login, it would be rather annoying for people to be changing other peoples things without knowing 2 sets in information. So the problem here is, the function itself actually works flawlessly, the Message produced which states SUCCESS or FAILURE always produces SUCCESS, even if the function failed (due to no match on one or more rows)

Here is the code used.

if(isset($_POST['upduserNotify'])){
    $ccurrentname = mysqli_real_escape_string($con, $_POST['ccnameVal']); 
    $cclientnotify = mysqli_real_escape_string($con, $_POST['cnotifyVal']);
    $cclientcpuk = mysqli_real_escape_string($con, $_POST['ccpukeyVal']);

    $changenot = "UPDATE clients SET notify = '$cclientnotify' WHERE cpukey = '$cclientcpuk' AND name = '".$_POST['ccnameVal']."'";

    if (mysqli_query($con, $changenot)) {
        echo'<div align ="center" style="color:#000000">Your Custom notification was updated successfully</div><br />';
    } else {
        echo'<div align ="center">You entered an incorrect CPUKEY/Name or used an invalid character</div><br />';
    }
}

An UPDATE query that runs, but finds no rows to update, is still a successful one - it ran to completion without encountering any errors, so mysqli_query will return TRUE , per the docs . (If it were a SELECT sort of query, it'd return a mysqli_result object.)

If you want to do something different when it didn't find any rows to update, you'll want to look at the number of affected rows and act accordingly.

        if(isset($_POST['upduserNotify'])){
            $ccurrentname = mysqli_real_escape_string($con, $_POST['ccnameVal']); 
            $cclientnotify = mysqli_real_escape_string($con, $_POST['cnotifyVal']);
            $cclientcpuk = mysqli_real_escape_string($con, $_POST['ccpukeyVal']);

        $changenot = "UPDATE `clients` SET `notify` = '$cclientnotify' WHERE `cpukey` = '$cclientcpuk' AND `name` = '$ccurrentname'";

                if (mysqli_query($con, $changenot) && mysqli_affected_rows($con) == 1 )
                {
                    echo'<div align ="center" style="color:#000000">Your Custom Xnotify was updated successfully</div><br />';
                } 
                else if (mysqli_query($con, $changenot) && mysqli_affected_rows($con) == 0 )
                {
                    echo'<div align ="center">You entered an incorrect CPUKEY/Name or used an invalid character</div><br />';
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM