使用循环错误的PDO结果

时间:2014-07-17 01:56:25

标签: mysql sql arrays string pdo

this question

连接

我有一个非常奇怪的问题。当我使用硬编码值从数组中检索数据并作为参数传递给PDO时,一切都很好。当我尝试使用任何循环时问题就变成了 - 结果是错误的。

此代码正常运行:

$tokenNo = 0;
$searchTokens = preg_split("/\s+/", $search_string);

$sql = "SELECT * FROM `users` WHERE ( (firstname LIKE :token" . $tokenNo . " OR
lastname LIKE :token" . $tokenNo . " OR phone LIKE :token" . $tokenNo . " OR
email LIKE :token" . $tokenNo . " OR username LIKE :token" . $tokenNo . ")";

for ($tokenNo=1; $tokenNo < count($searchTokens); $tokenNo++) { 
  $sql .= " AND (firstname LIKE :token" . $tokenNo . 
  " OR lastname LIKE :token" . $tokenNo . " OR phone LIKE :token" . $tokenNo .
  " OR email LIKE :token" . $tokenNo . " OR username LIKE :token" . $tokenNo . ")";
}
$sql .= " )";


if($query = $this->db->prepare($sql)) {
  $tokenNo = 0;
  $str1 = "%" . $searchTokens[$tokenNo] . "%";
  $query->bindParam(':token' . $tokenNo, $str1);

  $tokenNo = 1;
  $str2 = "%" . $searchTokens[$tokenNo] . "%";
  $query->bindParam(':token' . $tokenNo, $str2);

  $query->execute();

  $rows = $query->fetchAll(PDO::FETCH_ASSOC);

  var_dump($rows);
}

但这不是:

$tokenNo = 0;
$searchTokens = preg_split("/\s+/", $search_string);

$sql = "SELECT * FROM `users` WHERE ( (firstname LIKE :token" . $tokenNo . " OR
lastname LIKE :token" . $tokenNo . " OR phone LIKE :token" . $tokenNo . " OR
email LIKE :token" . $tokenNo . " OR username LIKE :token" . $tokenNo . ")";

for ($tokenNo=1; $tokenNo < count($searchTokens); $tokenNo++) { 
  $sql .= " AND (firstname LIKE :token" . $tokenNo . 
  " OR lastname LIKE :token" . $tokenNo . " OR phone LIKE :token" . $tokenNo .
  " OR email LIKE :token" . $tokenNo . " OR username LIKE :token" . $tokenNo . ")";
}
$sql .= " )";


if($query = $this->db->prepare($sql)) {
  $tokenNo = 0;

  while( $tokenNo < count(searchTokens) ) {
    $str1 = "%" . $searchTokens[$tokenNo] . "%";
    $query->bindParam(':token' . $tokenNo, $str1);
    $tokenNo++;
  }

  $query->execute();

  $rows = $query->fetchAll(PDO::FETCH_ASSOC);

  var_dump($rows);
}

如果我使用for循环,也会发生同样的情况。

错误的结果是显示太多数据 - 问题来自connected question

此致

1 个答案:

答案 0 :(得分:0)

根据Bind Param Manual给定参数必须参考...

我想到的最简单的解决方案是制作字符串数组:

while( $tokenNo < count(searchTokens) ) {
  $str[$tokenNo] = "%" . $searchTokens[$tokenNo] . "%";
  $query->bindParam(':token' . $tokenNo, $str[$tokenNo]);
  $tokenNo++;
}

现在它有效......