小野マトペの業務日誌(アニメ制作してない篇)

はてなダイアリーの閉鎖をうけ、旧ブログ http://d.hatena.ne.jp/ono_matope/ から移行しました。続きは→ http://matope.hatenablog.com/

PDO::MySQLでプレースホルダにバインドしたinteger変数がexecute後にstring化した

整数の$count変数をSQLプレースホルダにバインドしてexecuteして、結果行数と$count値を比較する、こういうコードを書いた

  1 <?php
  2 
  3   $pdo = new PDO("mysql:host=localhost;dbname=xxx",xxx,xxx);
  4   $count = 10;
  5   $sql = "select * from SEEDUSER limit :count;";
  6 
  7   echo "count is $count\n";
  8   echo "before prepare ".gettype($count)."\n";
  9   $stmt = $pdo->prepare($sql);
 10   echo "after prepare ".gettype($count)."\n";
 11   $stmt->bindParam(':count',$count,PDO::PARAM_INT);
 12   echo "after bind ".gettype($count)."\n";
 13   $stmt->execute();
 14   echo "after execute ".gettype($count)."\n";
 15   $result = $stmt->fetchAll();
 16 
 17   echo "result length is ".count($result)."\n";
 18   if(count($result) === $count){
 19     echo "count(result) === count\n";
 20   }else{
 21     echo "count(result) !== count\n";
 22   }
 23 ?>

出力はこうなった

count is 10
before prepare integer
after prepare integer
after bind integer
after execute string
result length is 10
count(result) !== count

SQL文のプレースホルダにバインドした整数型の$count変数が、$stmt->execute()後にstring型に変化していることがわかるだろうか。
このため、18行目の条件文では結果行数が$countと同じ時に真を期待していたが、実際には偽となっている。


なにこれこわい

実行環境

  1. CentOS 5
  2. php 5.2.6
  3. pdo_mysql 5.0.67