如何从SQL中的表中每次选择两行并在PHP中显示它们?

时间:2016-04-28 06:03:06

标签: php mysql

我的表格中包含iddateheadingnews等字段。我想在猫头鹰轮播滑块中显示字段dateheadingnews。任何人都可以建议如何从SQL表中一次选择两行,以便在Owl Carousel滑块中一次显示两个条目。我使用过这样的SQL查询:

<?php
$sql3 = "SELECT date, heading, news FROM news ORDER BY news.date LIMIT 0, 1";
$result3 = mysql_query($sql3) or die(mysql_error());
while($row3 = mysql_fetch_array($result3)) {
    ?>
    <div class="item ">
        <div class="l_blk">
            <div class="news_container">
                <div class="col-md-1 date_b"><p>Mar<br>09</p></div>
                <div class="col-md-11 cont_b">
                    <p>
                        <span class="news_t">"<?php echo $row3['heading']; ?>"</span><br>
                        <?php echo $row3['news']; ?>
                    </p>
                </div>
            </div>
        </div>
        <div class="l_blk">
            <div class="news_container">
                <div class="col-md-1 date_b"><p>Mar<br>09</p></div>
                <div class="col-md-11 cont_b">
                    <p>
                        <span class="news_t">"<?php echo $row3['heading']; ?>"</span><br>
                        <?php echo $row3['news']; ?>
                    </p>
                </div>
            </div>
        </div>
    </div>
    <?php
}
?>

有人可以建议怎么做吗?

2 个答案:

答案 0 :(得分:0)

$sql3 = "SELECT date, heading, news FROM news  ORDER BY news.date LIMIT 0, 1";

不要更改LIMIT 0,2

这意味着从索引0的值开始选择2?

完成后,取出循环中的重复代码

答案 1 :(得分:0)

试试这个。

<?php

$sql3 = "SELECT date, heading, news FROM news  ORDER BY news.date"; // No limit
$result3= mysql_query($sql3) or die(mysql_error());

$counter = 0;
while($row3 = mysql_fetch_array($result3, MYSQL_ASSOC))
{
    if($counter % 2 == 0){
        echo '<div class="item ">'.PHP_EOL;
    }
    ?>
        <div class="l_blk">

            <div class="news_container">

                <div class="col-md-1 date_b"><?php $row3['date'] ?></div>

                <div class="col-md-11 cont_b">

                    <p>

                        <span class="news_t">"<?php echo $row3['heading']; ?>"</span><br>

                        <?php echo $row3['news']; ?>

                    </p>

                </div>

            </div>

        </div>
<?php
    if($counter % 2 == 1){
    echo '</div>'.PHP_EOL;
    }
    $counter++;
}
if($counter % 2 == 1){
    echo '</div>'.PHP_EOL;
}
?>