douzhi3667 2015-05-22 09:18
浏览 27
已采纳

PDO MySQL产品循环

Im a real beginner when it comes to queries and PDO, i need some assistance in a project i am busy with. What i want to accomplish is to display products from the database. However the template style i am using forces me to show 3 products per row, is there a way to show 3 products per row and loop the code once there is more than 3 (if there is 5 products, the first 3 will display in the first row, and the rest in the second).

Here is the template i am using, note the div class "top-box", this forces that only 3 products can be shown per row.

<div class="top-box">
        <?php
        $sql = "SELECT * FROM _products WHERE category = '$cat'";
$result = dbConnect()->query($sql);
// If the SQL query is succesfully performed ($result not false)
if($result !== false) {
$cols = $result->columnCount();           // Number of returned columns
// Generate ADS Feed for each ROW
foreach($result as $row) {
                echo '<div class="col_1_of_3 span_1_of_3">
             <a href="product.php?i=' . $row['model'] . '">
                <div class="inner_content clearfix">
                <div class="product_image">
                    <img src="images/' . $row['model'] . '.jpg" alt=""/>
                </div>
                <div class="price">
                   <div class="cart-left">
                        <p class="title">' . $row['name'] . '</p>
                    </div>
                    <div class="clear"></div>
                 </div>             
               </div>
               </a>
            </div>';
            }
        } else {
            echo "<p>No products available at this moment, contact us for more information!</p>";
        }

        ?>

            <div class="clear"></div>
        </div>
  • 写回答

3条回答 默认 最新

  • dsxml2169 2015-05-22 09:35
    关注

    You can use a count variable inside your products foreach-loop. Every three products you can close the top-box and open a new one (This is an assumption as I don't know exactly how your styles work).

    At the end of the foreach-loop:

    if ($count != 0 && $count % 3 == 0) {
       echo '<div class="clear"></div>';
       echo '</div>';                    // close last .top-box
       echo '<div class="top-box">';
    }
    
    ++$count;
    

    I don't see how your question is connected to PDO. Keep in mind that using unescaped variables inside a query is potentially dangerous. Have a look here for some help: https://stackoverflow.com/a/60496/2516377

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题