[英]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.