即使尚未创建行,数据库查询也会执行

时间:2018-01-30 19:34:03

标签: php

我无法理解为什么mysqli_query在其中一个字段不存在的操作中返回true。当字段UPDATE与变量run_id匹配时,我正在尝试$id字段。但是,当$id未设置时,if语句内的echo将执行。非常感谢您对这一现象的看法。

function sumMiles($id,$runnerRow,$weekArray,$cnn){
    //Calculate cumulative miles per week for every runner
    $weekMiles=0; //total miles per week
    foreach($weekArray as $weekday)
        {
            $weekMiles+=$runnerRow[$weekday];
        }
        $addMiles = "UPDATE run SET weekly_total = {$weekMiles} WHERE run_id=$id";//add weekly total into the database's run table 
        if (mysqli_query($cnn,$addMiles)){
            echo "Your weekly total has been updated";
            return $weekMiles;
        }
        else {echo "Your weekly total could not be updated";}
    }

我这样称呼这个函数:

$weekMiles = sumMiles($id,$dailyMileage,$weekArray,$cnn);

1 个答案:

答案 0 :(得分:1)

该行存在的事实不会在数据库中生成任何异常。

在运行更新之前先验证是否存在该行

  select count(1) from  run WHERE run_id=$id

修改

您需要检查Count(1)是否大于0

$query = "SELECT count(1) from run WHERE run_id=$id"; 
if (mysqli_query($cnn,$query)>0){ 
 $addMiles = "UPDATE run SET weekly_total = {$weekMiles} WHERE run_id=$id"; 
 echo "updated"; 
}