1

我正在尝试使用 PDO 运行 FOREACH,但到目前为止,我的代码似乎只为 FOREACH 迭代一次并且只返回第一个值。

这是我所拥有的:

$colors = $_GET['color'];
$colors = explode(' ', $colors);
foreach ($colors as $color) 
    {
    $items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 = :colorbase1");
    $items -> bindValue(":colorbase1", $color);
    }
$items ->execute();
while($info = $items->fetch(PDO::FETCH_ASSOC)) 
{
echo $info['color_base1'];
}

请注意,$colors 包含从复选框和 jquery 获得的超过 1 种不同的颜色。

谢谢!

4

3 回答 3

3

您的代码嵌套错误:您想准备一次查询,并多次执行它,但您正在做相反的事情。

而不是:

foreach ( ... )
{
    prepare( ... );
    bind( ... );
}
execute();

你需要:

prepare( ... );
foreach ( ... )
{
    bind( ... );
    $results[] = execute();
}

或者,您可以使用 SQLIN子句来构建一个查询,而不是多次来回访问数据库的开销。

于 2012-08-21T16:03:16.257 回答
1

在这里试试这个:

<?php 
//Check your vars before setting!
$colors = (!empty($_GET['color'])?$_GET['color']:null);
$colors = explode(' ', $colors);

//Prepare the query once
$items = $con->prepare("SELECT * FROM item_descr WHERE color_base1 = :colorbase");
//Use bindParam then you can set $color later on
$items->bindParam(":colorbase", $color);

//Execute the query, iterating over each color
$results=array();
foreach ($colors as $color){
    $items->execute();
    //Fetch the result and store in $results
    $results[] = $items->fetchAll(PDO::FETCH_ASSOC);
}

//Loop through results
if(!empty($results)){
    foreach($results as $result) {
        foreach($result as $row){
            echo $row['color_base1'].'<br />';
        }
    }
}else{
    //empty
}
?>
于 2012-08-21T16:20:05.350 回答
0

你可以提供一个print_r$_GET['color']

这样做的原因 - 我认为如果你在 q 字符串中有空格,那么第一个空格将不会进一步发展,因此 foreach 只会运行一次。

于 2012-08-21T16:03:23.437 回答