我尝试使用PDO在MySQL中更新数据。
我已设置下面的代码,但收到错误
SQLSTATE [42000]:语法错误或访问冲突:1064>您的SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册>正确的语法,以便使用接近'(h1,text)值(' Blah blah' at line 1
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;
答案 0 :(得分:1)
更新语法应为:
UPDATE table_name SET `field1` = new-value1, `field2` = new-value2.
您的查询应该是:
UPDATE sections SET `h1` = :h1, `text` = :text WHERE id = 1;
答案 1 :(得分:0)
text是mysql中的reserved word。
按如下所示编写查询: -
UPDATE sections SET `h1` = :h1, `text` = :text WHERE id = 1;
希望它会对你有所帮助:)。