显示数据库中的最新3个结果

时间:2016-09-24 15:51:51

标签: php sql mysqli

我需要从数据库中单独显示最新的3篇文章(标题,描述,内容和图像)。

$title_query = "SELECT title, description, content, image FROM articles ORDER BY id DESC LIMIT 10";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));

while($row = mysqli_fetch_array($title_result)) 
{
$title = $row['title'];
$description = $row['description'];
$content = $row['content'];
$image = $row['image'];
}

echo $title;

目前这只是最新的一个。如何为第二个和第三个变量设置变量?所以我可以:

$title1
$title2
$title3

由于

2 个答案:

答案 0 :(得分:1)

你构建代码的方式,它应该回应第3项的细节。所以你应该做的就是循环并继续将它们添加到数组中,如下所示:

并且因为你想要最新的3件物品,所以你不能将它限制为只有3件物品如下:

$title = array();

$title_query = "SELECT title, description, content, image FROM articles ORDER BY id DESC LIMIT 3";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));

while($row = mysqli_fetch_array($title_result)) {
    $title[] = $row['title'];
}

print_r($title);

答案 1 :(得分:0)

您根据发布到数据库中的id单独显示最新文章的请求。你需要修改你提供给问题的循环。

如果您想在任何循环语句之外显示多个产品,您必须将其存储在array()中,之后您可以use在其他地方outside the loop

为了将变量作为数组,您可以根据需要在两种方法中的任何一种中初始化array()

方法:1 - 当查询返回TRUE值时,您可以初始化array()

方法:2 - 您也可以初始化页面顶部的array()

初始化基于开发代码的开发人员的便利性。

MYSQL限制声明的基本策略。

  

MySQL:SELECT LIMIT Statement

描述: MySQL SELECT LIMIT语句用于从MySQL中的一个或多个表中检索记录,并根据限制值限制返回的记录数。

<强>语法:

MySQL中SELECT LIMIT语句的语法是:

SELECT expressions
FROM tables
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]]
LIMIT row_count

因此您需要修改如下查询,以便根据您的要求显示最新的三篇文章。

<?php
$title_query = "SELECT `title`, `description`, `content`, `image` FROM `articles` ORDER BY `id` DESC LIMIT 0,3";
$title_result = mysqli_query($con, $title_query) or die(mysqli_error($con));
$counting = $title_result->num_rows;
if($counting==0)
{
    echo 'No Datas found';
}
else
{
// This part will execute if the count is greater than 0
$row=[];
while($fetch = $title_result->fetch_assoc()) {
    $row[] = $fetch;
}
}

// here you can loop through to display the data.
foreach ($row as $key => $single_data) {
?>
    Title: <?php echo $single_data['title']; ?>
    Description: <?php echo $single_data['description']; ?>
    Content: <?php echo $single_data['content']; ?>
    Image: <img src="PATH to FOLDER WHERE YOU HAVE SAVED THE IMAGE ALONG WITH <?php echo $single_data['image']; ?>" />
<?php   
}
?>
相关问题