首页 > 解决方案 > 更新记录时出错:您的 SQL 语法有误;检查手册

问题描述

这是我的代码,但我有错误

更新记录时出错:您的 SQL 语法有误;检查与您的 MariaDB 服务器版本相对应的手册,以获取正确的语法,以便在第 9 行的 '' 附近使用

<?php
$conn = mysqli_connect("localhost", "root", "", "physical_therapy");
$conn->query("SET NAMES UTF8");

$id = $_POST["id"];
$fn = $_POST["Cus_Name"];
$age = $_POST["Cus_Age"];
$address = $_POST["Cus_Address"];
$phone = $_POST['Cus_Phone'];
$em = $_POST['Cus_Email'];
$pwd = $_POST["Cus_Password"];
$gender = $_POST["Cus_Gender"];



if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "UPDATE customer SET 
Cus_Name='" . $fn . "', 
Cus_Age='" . $age . "', 
Cus_Address='" . $address . "', 
Cus_Phone='" . $phone . "',
Cus_Password='" . $pwd . "', 
Cus_Email='" . $em . "',
Cus_Gender='" . $gender . "' 
WHERE Cus_id=" . $id;

if (mysqli_query($conn, $sql)) {
    echo "Update Successfully!!<br><br>";
    echo "<a href=\"ProfileCus.php\">Go to Home</a>";
} else {
    echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn); ?>

标签: phpmysqli

解决方案


查询不起作用可能有两个原因:

  • 您的数据中有一个'正在破坏您的 SQL。
  • $id是空的。

您还应该使用准备好的语句来避免 sql 注入:

$conn = mysqli_connect("localhost", "root", "", "physical_therapy");
$conn->query("SET NAMES UTF8");

$id = $_POST["id"];
$fn = $_POST["Cus_Name"];
$age = $_POST["Cus_Age"];
$address = $_POST["Cus_Address"];
$phone = $_POST['Cus_Phone'];
$em = $_POST['Cus_Email'];
$pwd = $_POST["Cus_Password"];
$gender = $_POST["Cus_Gender"];

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = 'UPDATE customer SET Cus_Name = ?, Cus_Age = ?, Cus_Address = ?, Cus_Phone = ?, Cus_Password = ?, Cus_Email = ?, Cus_Gender = ? WHERE Cus_id = ?';

if ($stmt = mysqli_prepare($conn, $sql)) {
    $stmt->bind_param('s', $fn);
    $stmt->bind_param('i', $age);
    $stmt->bind_param('s', $address);
    $stmt->bind_param('s', $phone);
    $stmt->bind_param('s', $pwd);
    $stmt->bind_param('s', $em);
    $stmt->bind_param('s', $gender);
    $stmt->bind_param('i', $id);

    if ($stmt->execute()) {
        echo "Update Successfully!!<br><br>";
        echo "<a href=\"ProfileCus.php\">Go to Home</a>";
    } else {
        echo "Error updating record: " . mysqli_error($conn);
    }
}

mysqli_close($conn);

推荐阅读