0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PHP】PDOのプリペアドステートメントのプレースホルダーについてのTips

Posted at

環境

PHP:7系
DB:SQLServer
現象:プリペアドステートメントのバインドでエラーになる。

発生するエラーの例

〜 COUNT field incorrect or syntax error in 〜

サンプルコード

$user_code = '001';

$user_name = 'taro';

$con = new PDO ("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");


$sql = <<< SQL

            INSERT INTO
                test_table
        
                (
                    [登録者コード],
                    [登録者名],        
                    [変更者コード]
        
                )
            VALUES
                (
                    :user_code,
                    :user_name,
                    :user_code
                );
SQL;

$hash = [
            ':user_code' => $user_code,
            ':user_name' => $user_name
];

$stmt = $con->prepare($sql);

foreach($hash as $key => $val) {

    $stmt->bindValue($key, $val, PDO::PARAM_STR);

}

$stmt->execute();

この時、登録者コードと変更者コードは同一の値をバインドしたいので、どちらも「':user_code' => $user_code」
でいいのですが、実はこれだとエラーになります。

解決策

プレースホルダーの名前をそれぞれ別のものに設定すれば解決します。

現状

            VALUES
                (
                    :user_code,        
                    :user_name,
                    :user_code
                );

$hash = [
            ':user_code' => $user_code,
            ':user_name' => $user_name
];                

修正後

            VALUES
                (        
                    :created_by,        
                    :user_name,        
                    :updated_by        
                );

$hash = [
            ':created_by' => $user_code,
            ':user_name'  => $user_name,
            ':updated_by' => $user_code
];                

上記のようにそれぞれ別のプレースホルダー名に修正することでエラーが無くなります。

実装していた時、AIツールに質問したら「':user_code' => $user_code,」のように一回の記述で複数のプレースホルダーにバインドするという答えが返ってきたがその後エラーになってしまったので、その後色々と調べた結果今回の箇所がエラーの原因だったことに気が付いた。

今回は以上になります。ありがとうございました:relieved:

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?