fetchAll()返回值为0的数组(PDO)

时间:2014-03-06 02:40:40

标签: php pdo

我正在尝试将值绑定到SQL语句中。它似乎没有约束力,或者正在工作,并且没有返回所需数据,原因是我不知道。这是我的代码:

$search_string = 'turkey';

// Gathers the bird ID through searched name
$birdID = $conn->prepare("SELECT `id` FROM `birds` WHERE `bird_name` LIKE :birdName ;");    
$birdID->execute(array(':birdName' => '%'.$search_string.'%'));  
$returnBirdID = $birdID->fetchAll(PDO::FETCH_BOTH);

foreach($returnBirdID as $birdID){
    $birdsID[] = $birdID;
}

重要的是要注意var_dump($ birdsID)按预期返回一个数组。

我有另一个类似于上面的代码块,它根据状态缩写检索数据,例如: “NY”。为简洁而离开它(它几乎与上面相同)。

// Build query for binding.

$sql = "
              SELECT t.state_id,t.bird_id
              FROM table1
              WHERE bird.id = :birdID 
              AND states.id = :statesID ;
          ";
$query = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$query->execute(array(':birdID'=>$birdsID,':statesID'=>$statesID));// Think this line may be the problem...
$results = $query->fetchAll(PDO::FETCH_BOTH);

foreach($results as $getID){
    $getIDs[] = $getID;
}

var_dump($ getIDs)在这里返回NULL。我认为它可能与:birdID'=> $ birdsID不接受$ birdsID作为值,因为它本身就是一个数组。但将其编码为$ birdsID [0]也不起作用。不知道发生了什么事!

哇......这几个小时都在努力。如果它没有意义,抱歉!大脑炒了。

1 个答案:

答案 0 :(得分:1)

在PDO标记(info)中,您将找到在参数中使用通配符的正确过程。 PDO Tag

$search_string = '%turkey%';

// Gathers the bird ID through searched name
$birdID = $conn->prepare("SELECT `id` FROM `birds` WHERE `bird_name` LIKE :birdName ;");    
$birdID->execute(array(':birdName' => $search_string));  
$returnBirdID = $birdID->fetchAll(PDO::FETCH_BOTH);

foreach($returnBirdID as $birdID){
    $birdsID[] = $birdID;
}