【问题标题】:Display entries from a database, list them from newest to oldest and stop after a certain amount?显示数据库中的条目,从最新到最旧列出它们并在一定数量后停止?
【发布时间】:2012-07-25 19:30:26
【问题描述】:

我的数据库中有以下表格:

  1. 身份证
  2. 标题
  3. 标题
  4. 内容
  5. 日期
  6. 标签
  7. 用户名
  8. 喜欢
  9. 不喜欢
  10. cmets

我已连接数据库,以便它显示行中的内容,但我不知道如何制作它,以便每次创建新条目时它都会生成并列出一个“帖子块”。我还想将它们从最新帖子到最旧帖子列出,同时将帖子限制为每页 10-20 个。

<?php

$connect = mysql_connect('localhost','root','','andrewryan') or die('error connection');

mysql_select_db('andrewryan');

$query = "Select * FROM entry";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

$username = $row['username'];
$title = $row['title'];
$heading = $row['heading'];
$content = $row['content'];
$tags = $row['tags'];
$like = $row['like'];
$dislike = $row['dislike'];
$comment = $row['comment'];
$date = $row['date'];
?>

我还有一个只有一个 html 块的页面。这是 post 框架,所有变量都在需要的地方给出。如果有帮助,可以在此链接中找到有关我的目标的任何参考:HERE

【问题讨论】:

  • 你也可以发布代码吗?
  • 你有没有尝试过?
  • 你试过什么?查看ORDER BYLIMITdev.mysql.com/doc/refman/5.5/en/select.html 否决了,因为您似乎没有进行任何尽职调查。
  • 这个网站上有几百万个关于如何对数据库结果进行分页的问题/答案。

标签: php mysql database post blogs


【解决方案1】:

就查询而言:

// Tildes on date since it is a keyword and some databases will error out without them
// Order by date is if you are using a compatible storing: unix timestamp or DateTime field
$query = "Select * FROM entry ORDER BY `date` DESC";
$result = mysql_query($query);
$rowCount = 0;
while($row = mysql_fetch_array($result)) {
    $username[$rowCount] = $row['username'];
    $title[$rowCount] = $row['title'];
    $heading[$rowCount] = $row['heading'];
    $content[$rowCount] = $row['content'];
    $tags[$rowCount] = $row['tags'];
    $like[$rowCount] = $row['like'];
    $dislike[$rowCount] = $row['dislike'];
    $comment[$rowCount] = $row['comment'];
    $date[$rowCount] = $row['date'];
    $rowCount++;
}

这只是显示帖子:

// limit is used to show the max posts per page.
$limit = 20;

//The following for is for paging
for($i = 1; $i <= $numofpages; $i++){
    if($i == $page){
        echo $i . " ";
    }else{
        echo "<a href='page.php?page=" . $i . "'>" . $i . "</a> ";
    }
}

// The following is to show your post blocks
for($j = 0; $j < $limit; $j++){
    //This will give you the appropriate post for the page
    $temp = $j + (($page * $limit) - $limit);
    // Your code to show your post blocks
    echo $username[$temp]; //For example, just format for your site layout.
}

【讨论】:

    【解决方案2】:
    1. 选择您有兴趣获取的所有字段。
    2. 使用 DATE_FORMAT 函数格式化日期字段并分配给新别名。我将其命名为 ndate。
      1. 然后按日期订购

    SELECT username,title,heading,content,tags,like,dislike,comment,DATE_FORMAT(date, '%d-%M-%Y') AS ndate FROM entry ORDER BY ndate

    获取日期为 $row['ndate']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-06
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      相关资源
      最近更新 更多