dongmaopan5738 2014-09-16 11:53
浏览 39
已采纳

需要在查询中格式化PHP结果

I am a Monkey see Monkey do Programmer. so at my age to old to learn anything new. I do need some advice and help!

I need to pull data from a table. (See table fields below)

  • ID
  • Title
  • DatePosted
  • Description
  • Picture

(This i can do and list them perfectly below each other) using

<?php 
    try {
        $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
        $conn->exec("SET CHARACTER SET utf8");// Sets encoding UTF-8
        $sql = "select * from TableNews Order by DatePosted ASC LIMIT 5 " ;
        $result = $conn->query($sql);
        if($result !== false) {
            $cols = $result->columnCount();
            foreach($result as $row) {
                echo $row['Title'] . "
";
                echo $row['DatePosted'] . "
";
            } 
        }
        $conn = null;
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
?>

This works perfect !!!

Here is where i need advice.

In my results i need the first record that comes out to only list the title and the picture anbd the remaining 4 Records only to show the -Title -DatePosted -Description.

Much of a Muchness like the news image included here

Thank you

screen capture i took from Fox News

  • 写回答

2条回答 默认 最新

  • duanhuo7441 2014-09-16 12:07
    关注
    <?php try {
        $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
        $conn->exec("SET CHARACTER SET utf8");// Sets encoding UTF-8
        $sql = "select * from TableNews Order by DatePosted ASC LIMIT 5 " ;
        $result = $conn->query($sql);
        if($result !== false) {
        $cols = $result->columnCount();
        $rowcount = 0;
        foreach($result as $row) {
        if ($rowcount==0) {
            echo $row['picture']."<br>";
            $rowcount++;
        } else {
            echo $row['Title']." - ".$row['DatePosted'];
        }
        if ($rowcount==4) {
            $rowcount=0;
        }    
    
        } 
        }
        $conn = null;
        }
        catch(PDOException $e) {
        echo $e->getMessage();
        }
        ?>
    

    Something like this where you set the counter initially to zero then increment it for each row to display when its hit your 4th row then reset the counter to zero so it'll repost the picture. (this last stage is only required if you're planning on using multiple header images every 5th display otherwise you can remove the 2nd iff statement with $rowcount==4

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看