2016-09-24 29 views
-2

我需要從數據庫(標題,說明,內容和圖像)中單獨顯示最新的3篇文章。顯示數據庫的最新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

您需要while循環和限制內部回聲3查詢 – Alephtus

+0

使用數組的標題,描述......像'$標題[] = $行[「標題」]; ' –

+0

@ legolas1211。我已經提供瞭解決方案。試試看,如果你發現任何障礙,讓我知道。 –

回答

1

您構建代碼的方式,它應該是呼應了第3項的絲毫不差。所以你應該做的是經過循環,並不斷將其添加到陣列象下面這樣:

既然你想要最新的3項,所以WHT你不限制它只有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); 
0

請求您根據發佈到數據庫中的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 
} 
?>