PHP MySQL语法字符串错误

时间:2016-01-18 23:06:38

标签: php mysql

我遇到了关于中断MySQL查询的字符串的语法问题。 或者我错了吗?

while($row = $result->fetch_assoc()) {      
    $minuts = $minut *60+3600;

    $new_plan = strtotime($row['på_gulvet_rigtig'])+$minuts;

    $new_plan = gmdate("H:i", $new_plan);
    $new_plan = $new_plan;

    echo $new_plan,"<br>";

    $sql1 = ("UPDATE lokal set på_gulvet_planen = " .  $new_plan . " WHERE Id = ". $row['Id'] . "");
    if (mysqli_query($conn, $sql1)) {
        echo "Record updated successfully <br>";
    } 
    else {
        echo "Error updating record: " . mysqli_error($conn), "<br>";
    }
}

输出:

  

12:40

     

更新记录时出错:您的SQL语法出错;检查   手册,对应右边的MySQL服务器版本   在第1行':40 WHERE Id = 1'附近使用的语法

1 个答案:

答案 0 :(得分:2)

您在执行查询之前没有准备好查询,因此您放置数据的任何文本列都需要用引号括起来,比如

$sql1 = ("UPDATE lokal 
         set på_gulvet_planen = '" . $new_plan . "' 
         WHERE Id = ". $row['Id'] );

如果使用此构造

,可以使字符串更易于阅读,因此可以进行调试
$sql1 = ("UPDATE lokal 
         set på_gulvet_planen = '$new_plan' 
         WHERE Id = {$row['Id']}");

注意当数据不是标量变量时使用大括号,即{$row['Id']}

使用像这样的预备语句

也会更好
$sql1 = ("UPDATE lokal 
         set på_gulvet_planen = ? 
         WHERE Id = ?");
$stmt = mysqli_prepare($conn, $sql1);
if ( $stmt === FALSE ) {
    echo 'Query Error ' . mysqli_error($conn);
    exit;
}

mysqli_stmt_bind_param($stmt, "s", $new_plan);
mysqli_stmt_bind_param($stmt, "i", $row['Id']);
$result = mysqli_stmt_execute($stmt);
if ( $result === FALSE ) {
    echo "Error updating record: " . mysqli_error($conn), "<br>";
} else {
    echo "Record updated successfully <br>";
}