如何计算mysql中的所有行,但只显示2个结果并计算所有结果

时间:2015-06-13 16:44:19

标签: php

我试图从数据库中显示我的数据。更精确的是图像。问题是当我必须提取超过2个图像。然后我想只显示前两个图像和打印例如添加了49个图像或我从mysql中提取了多少图像。我的脚本在这里:

public function getImages($id, $username){
    global $con;
    $stm = $con->prepare("SELECT * FROM image WHERE postId = :id AND author = :username");
    $stm->execute(array(":id" => $id, ":username" => $username));
    $imagesNum = $stm->rowCount();
    if($imagesNum == 1){
        $image = $stm->fetch(PDO::FETCH_OBJ);
        echo '<div class="frame"><div class="frameOneImage"><img src="../upload/img/'.$username.'/'.$image->path.'"></div></div>';
    } else if($imagesNum == 2){
        echo '<div class="frame">';
        $row = $stm->fetchAll();
        foreach($row as $image){
            echo'<div class="frameTwoImages"><img src="../upload/img/'.$username.'/'.$image['path'].'"></div>';
        }
        echo '</div>';
    } else {
        // HERE I WANT TO DISPLAY ONLY TWO IMAGES BUT IT WRITE ADDED (NUMBER OF ALL IMAGES EXTRACTED)
    }
}

3 个答案:

答案 0 :(得分:1)

我可以想到两种方法来实现这一目标:

第一个解决方案

使用子查询执行查询。主查询只返回两行,子查询将返回总图像数。

这样的事情:

SELECT *, (SELECT COUNT(*) FROM image WHERE postId = :id AND author = :username) as totalRows FROM image WHERE postId = :id AND author = :username LIMIT 2

第二个解决方案

您的查询就像您现在正在执行此操作并执行仅打印两张图像的循环。

 $row = $stm->fetchAll();
 $totalRows = $stm->rowCount();

 // This loop will print only two rows
 for($i = 0; i < 2; $i++) {
     echo $row[$i]; 
 } 
 echo "Total rows " . $totalRows;

我个人更喜欢第一个,因为它只返回两行加上数据库中的总项数而不是总行数,只打印第二个解决方案中的两个。

答案 1 :(得分:1)

您可以将变量设置为递增,然后在两次迭代后退出for循环,如下所示:

else {
    echo '<div class="frame">';
    $row = $stm->fetchAll();
    $i = 0;
    foreach($row as $image){
        echo'<div class="frameTwoImages"><img src="../upload/img/'.$username.'/'.$image['path'].'"></div>';
        if ($i >= 2) {
            echo 'Only first two results showing. ' . $imageNum . ' results have been omitted.';
            break;
        } else {
            $i++;
        }
    }
}

答案 2 :(得分:0)

public function getImages($id, $username){
    global $con;
    $stm = $con->prepare("SELECT * FROM image WHERE postId = :id AND author = :username");
    $stm->execute(array(":id" => $id, ":username" => $username));
    $imagesNum = $stm->rowCount();
    $row = $stm->fetchAll();
    for($i=0; $i<2; $i++){
        if(isset($row[$i])){
             echo '<div class="frame"><div class="frame($imagesNum == 1 ? 'OneImage' : 'TwoImages')"><img src="../upload/img/'.$username.'/'.$row[$i]->path.'"></div></div>';
        }
    }
    if($imagesNum > 2) {
        echo '<span>'.$imagesNum.' images total</span>';
    }
}