実現したいこと
フォームから入力されたidが存在するときデータを更新したい
元の値
id | title | body |
---|---|---|
1 | xxx | zzz |
更新後(フォームで入力した値)
id | title | body |
---|---|---|
1 | zzz | yyy |
前提
入力フォームで入力したデータを送信する際にエラーが発生している。
データベースは接続できている
テーブル作成済み
更新処理のためにあらかじめデータ用意済
発生している問題・エラーメッセージ
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
該当のソースコード
php
1<?php 2 3$db_host =xxxx 4$dsn = xxxx 5$user = xxxx 6$password = xxxx 7 8try { 9 $dbh = new PDO($dsn, $user, $password); 10} catch (PDOException $e) { 11} 12 13?> 14 15<!DOCTYPE html> 16<html> 17 18<form method="post"> 19 <p>ID:<input type="text" name="id" /></p> 20 <p>タイトル:<input type="text" name="title" /></p> 21 <p>内容:<textarea type="text" name="body" rows="3"></textarea></p> 22 <button>送信</button> 23</form> 24<h1>メッセージ</h1> 25<div name="ans" style="border: 1px solid;padding:10px"> 26 <?php 27 // PHP8から$_POSTは未定義扱いになりエラーがでるので、issetで回避する 28 if (isset($_POST['title']) || isset($_POST['body']) || isset($_POST['id'])) { 29 // 現在日時 30 $input_datetime = date("Y-m-d H:i:s"); 31 // 更新対象のID 32 $id = $_POST['id']; 33 // 更新SQL 34 $sql = "update testtable set (title = :title, body = :body, updated_at = :updated_at where id = $id)"; 35 $stmt = $dbh->prepare($sql); 36 $stmt->bindValue(':title', $_POST['title']); 37 $stmt->bindValue(':body', $_POST['body']); 38 $stmt->bindValue(':updated_at', $input_datetime); 39 40 //idが0件の場合の処理 41 $id_check = "select title, body from testtable where id = $id"; 42 $result = $dbh->query($id_check); 43 $count = $result->rowCount(); 44 if ($count == 0) { 45 echo '更新対象が見つかりません'; 46 } 47 //実行結果 48 if ($stmt->execute()) { 49 echo ' 更新完了しました'; 50 } else { 51 echo '更新に失敗しました'; 52 } 53 } 54 ?> 55</div> 56 57</html>
試したこと
SQLSTATE[42000]: Syntax error シンタックスエラー(SQL文法間違い)
とあるので、
update構文の見直し(お作法等が間違っていないか)をしたが、正しい形になっていると思うので
どこに原因があるかわからない
補足情報(FW/ツールのバージョンなど)
php8
mysql
vscode

回答1件
あなたの回答
tips
プレビュー