在foreach循环中选择具有特定索引的行

时间:2017-06-23 22:04:31

标签: php mysql pdo foreach

我想输出特定产品的所有图像文件。输出第1行,第2行,第3行等图像路径的正确语法是什么?我找不到它了。

            $sql = "SELECT *
                    FROM images
                    WHERE productid = $productid"; 

            $select = $db->prepare($sql);
            $select->execute(array());      


        foreach($select as $index => $rs) {

        if($rs['imagepath']){
             if($index == 0){
               echo $imagepath[0];  // <---What is the right sytax of this?
           }
        }

       if($rs['imagepath']){
            if($index == 1){
                echo $imagepath[1]; // <---and this?
           }
       }

      if($rs['imagepath']){
            if($index == 3){
                echo $imagepath[2]; // <---and this?
           }
       }

3 个答案:

答案 0 :(得分:0)

$rows = [];

            $sql = "SELECT *
                    FROM images
                    WHERE productid = productid"; 

            $select = $db->prepare($sql);
            $select->execute(array());      


        foreach($select as $index => $rs) {
        $rows []= $rs;

       }
                echo $rows[0]['imagepath'];

答案 1 :(得分:0)

是不是我们错过了获取功能? `

$select = $db->prepare($sql);
$select->execute(array());      

$i = 0;
while($row = $select->fetch()) {
   echo $i . ' '. $row['imagepath'] . '<br>';
   $i++;
}

&GT?; `

- 附录: 我现在明白你只想要显示一个或一些图像。 那么,只选择那些/那些图像会不容易吗?

SELECT imagepath FROM images WHERE productid = productid AND someid = 3

或者如果没有“someid”:

SELECT imagepath FROM images WHERE productid = productid LIMIT 2,1

这样可以避免循环可能是100条记录只能使用第3条。

答案 2 :(得分:0)

一个foreach循环的重点是每次选择一次作为&#34; index&#34;。所以你不必担心为每个可能的行创建一个if语句,只需要声明一次,它将在每次迭代时发生