PHP数据库查询

时间:2012-01-13 17:52:30

标签: php mysql database

我有商业目录网站,我希望它像Craigslist那样成为所有帖子的组。

目前我的数据会像这样出现在网站上

<business name1> <phone number> <jan 13 2012>
<business name2> <phone number> <jan 13 2012>
<business name1> <phone number> <jan 12 2012>

我想像这样布局,所以帖子将按发布日期进行分组。

<jan 13 2012>
<business name1> <phone number>
<business name2> <phone number>

<jan 12 2012>
<business name1> <phone number>
<business name2> <phone number>

这是我的编码

connection 
$query = "SELECT * FROM `myname` ORDER BY `myname`.`id` DESC LIMIT $offset, $limit ";
$result = mysql_query($query);


    while($row = mysql_fetch_row($result))

    {   

?>

<div class="list">
 <div class="ads_name"><a href="http://www.mydomain.com/category/<?=$row[0]?>.html" target="_blank"><?=$row[4]?> </a></div>
    <div class="location"><?= htmlspecialchars($row[5])?></div>
    <div class="phone"><?=formatPhoneNumber($row[3])?></div>
    <div class="date"><?=$row[9]?></div>
</div>

<?php
    }
    mysql_free_result($result);
?>

1 个答案:

答案 0 :(得分:1)

首先你需要像

这样的东西
SELECT * FROM `myname` ORDER BY `myname`.`mydate` DESC, `myname`.`id` DESC LIMIT $offset, $limit

确保您的行以正确的顺序到达。接下来,您要进行经典的组更改算法:

<?php
...

    $date='__invalid__';
    while($row = mysql_fetch_row($result))

    {   

      if ($row[9]!=$date)
      {
        $date=$row[9];
?>
<div class="date_header"><?=$row[9]?></div>

<?php
      }
?>

<div class="list">
 <div class="ads_name"><a href="http://www.mydomain.com/category/<?=$row[0]?>.html" target="_blank"><?=$row[4]?> </a></div>
    <div class="location"><?= htmlspecialchars($row[5])?></div>
    <div class="phone"><?=formatPhoneNumber($row[3])?></div>
    <div class="date"><?=$row[9]?></div>
</div>

<?php
    }
    mysql_free_result($result);
?>