0
1

More than 3 years have passed since last update.

executeでfatal errorが発生。原因はbindValueの引数だった(PHP)

Posted at

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

0
1
0

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
1