[英]Display the latest 3 results from database
我需要从数据库中单独显示最新的 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
等等。
谢谢
你构建代码的方式,它应该呼应第三项的标题。 所以你应该做的是通过循环并继续将它们添加到数组中,如下所示:
并且由于您想要最新的 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);
您根据发布到数据库中的id
单独显示最新文章的请求。 您需要修改您提供给问题的循环。
如果你想显示多个产品,您有任何循环语句的外面,使其存储值的array()
之后,你可以use
其他地方outside the loop
。
为了使变量成为数组,您可以根据需要在两种方法中的任何一种中初始化array()
。
方法: 1 - 您可以在查询返回 TRUE 值时初始化array()
。
方法:2 - 您也可以在页面顶部初始化array()
。
初始化是基于开发代码的开发人员的方便性。
MYSQL 限制语句的基本策略。
MySQL:SELECT LIMIT 语句
描述: 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
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.