从数据库中检索最新记录并在正文中显示?

时间:2014-03-22 04:16:56

标签: php html mysql database

我正在建立一个数据库驱动的网站。但在我购买.com域名之前,我的目标是让网站更具活力。互动。不知怎的,我陷入了mySQL和PHP的困境。我是mySQL的新手,对PHP知之甚少。我能够运行页面生成器代码,剩下的就是动态主页代码。

所以,我想从我的数据库中获取5条最新记录并将其显示在我主页的格式化DIV框中。我有一个示例代码,但记录显示在循环数组中。如何获取这些数据并将它们存储在$变量中,以便我可以在我的DIV框中回显它。

我的网站: ASCAS.tk

我如何从这5行中分配每个数据的变量? 恩。 ($ id_1,$ id_2,$ id_3,$ title_1,$ title_2,$ title_3 ......)


我还有一个PHP代码,可以在一个表中显示所有记录。

<?php
$con=mysqli_connect("localhost","user","pass","u967445970_home");
if (mysqli_connect_errno())
{echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$result = mysqli_query($con,"SELECT * FROM main");

echo "<table border='1'>
<tr>
<th>id</th>
<th>Title</th>
<th>Description</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['Title'] . "</td>";
echo "<td>" . $row['Description'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

我如何从这5行中分配每个数据的变量? 恩。 ($ id_1,$ id_2,$ id_3,$ title_1,$ title_2,$ title_3 ......)

3 个答案:

答案 0 :(得分:1)

使用此

更改结果变量
$result = mysqli_query($con,"SELECT * FROM main LIMIT 5");

如果你想订购你的最后一条记录(假设在这种情况下,我想按日期订购),这就是代码

$result = mysqli_query($con,"SELECT * FROM main order by id DESC LIMIT 5");

使用主键更改id

答案 1 :(得分:0)

试试这个

$result = mysqli_query($con,"SELECT * FROM main order by created_date DESC LIMIT 2");

或试试这个

$result = mysqli_query($con,"SELECT * FROM main order by id DESC LIMIT 2");

答案 2 :(得分:0)

使用此查询

 <?php
$con=mysqli_connect("localhost","user","pass","u967445970_home");
if (mysqli_connect_errno())
{echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$result = mysqli_query($con,"SELECT * FROM main order by date desc limit 0, 5");

if(mysqli_num_rows($result)> 0){ 
echo "<table border='1'>
<tr>
<th>id</th>
<th>Title</th>
<th>Description</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['Title'] . "</td>";
echo "<td>" . $row['Description'] . "</td>";
echo "</tr>";
}
echo "</table>"; 
}
mysqli_close($con);
?>