pdoでlimit句に対してbindParam, bindValueするとエラー

例えば

 

$sth = $dbh->prepare('SELECT name, colour, calories

    FROM fruit

    WHERE calories < :calories LIMIT :limit');

$sth->bindValue(':calories', $calories);

$sth->bindValue(':limit', $limit);

$sth->execute();

 

のように,limit句に名前付けプレースホルダなどで値をバインドした場合,executeの結果がfalseになってしまう.

 

これはlimit句に渡す値が文字列扱いになっているためらしい.

ということで次のように書き換えて実行したところ通った.

 

$sth = $dbh->prepare('SELECT name, colour, calories

    FROM fruit

    WHERE calories < :calories LIMIT :limit');

$sth->bindValue(':calories', $calories);

$sth->bindValue(':limit', (int)$limit, PDO::PARAM_INT);

$sth->execute();

 

limitに値をバインドするときは,明示的に数値に変換するのと,パラメータのタイプ定数を渡して指定しましょう.