executeでfatal errorが発生。原因はbindValueだった
【エラーが出たコード】
$name = John;
$id = 1;
$sql = SELECT * FROM bbs WHERE name? OR id=?
$statement = prepare($sql);
$statement->bindValue(1, $name);
$statement->bindValue(2, $id);
$statement->execute();
fatal error:C in...
みたいなエラーが出て原因がさっぱりわからない!
少し勉強をしたことのある方でしたらパッと見てここが原因だなとお分かりになるかもしれませんが、
私は気付くのに何時間もかかってしまいました。
答えはbindValueの第三引数!
bindValueはの第三引数は入力しないと初期値でSTR型が設定されることになっています。
そこに数値型を入力していたためエラーが出ていました。
bindValueを使用するときは面倒でも
$statement->bindValue(1, $name, PDO::PARAM_STR);//STR型
$statement->bindValue(2, $id, PDO::PARAM_INT);//INT型
のように第三引数を指定してあげるとこのようなミスは防げますね。
プログラミング初心者で詰まった方の参考になると嬉しいです。
参考
[PHP公式ドキュメント] https://www.php.net/manual/ja/pdostatement.bindvalue.php