PHP使用PDO更新MySQL中的数据[duplicate]

kokeuurv  于 2022-11-21  发布在  PHP
关注(0)|答案(2)|浏览(124)

此问题在此处已有答案

Sql syntax error using UPDATE database query [closed](2个答案)
六年前就关门了。
我正在尝试使用PDO更新MySQL中的数据。
我已经设置了下面的代码,但得到错误
数据库状态[42000]:语法错误或访问冲突:1064 1064您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册〉以获取使用near '(h1,text)值(第1行的' blah blah')的正确语法

if (isset($_POST['Submit']))://if admin wants to edit category

$h1 = $_POST['h1'];
$text = $_POST['text'];

$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "dbname";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Prepare statement
$stmt = $conn->prepare('UPDATE sections (h1, text) values (:h1, :text) WHERE id=1');
$stmt->bindParam(':h1', $h1);   
$stmt->bindParam(':text', $text);   
// execute the query
$stmt->execute();

// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
nafvub8i

nafvub8i1#

更新语法应为:

UPDATE table_name SET `field1` = new-value1, `field2` = new-value2.

您的查询应该是:

UPDATE sections SET `h1` = :h1, `text` = :text WHERE id = 1;

请参阅Update query syntax

gev0vcfq

gev0vcfq2#

文本是mysql中的reserved word
按以下方式编写查询:-

UPDATE sections SET `h1` = :h1, `text` = :text WHERE id = 1;

相关问题