利用自增字段,把要查询的数据表的id设置为自增。查询数据时,order by id desc,取第一条就是最新的。
利用时间,要查询的数据表中增加时间字段,查询时,order by time desc,取第一条就是最新的。
试编写代码示例如下:
<?php//连接数据库
$db = new mysqli('localhost','test','test','test')
if ($db->connect_errno) {
printf("连接数据库失败: %s\n", $db->connect_error)
exit()
}
//对数据库根据时间字段按降序排序,并抽取前面的40条记录
$data = $db->query('select * from 数据表名 order by 时间字段名 desc limit 40')
$rows = $data->fetch_all(MYSQLI_ASSOC)
//随机生成 5 条记录数组
$rand_arr = array_rand($rows, 5)
//根据生成的随机数组,输出记录
for($i=0$i<5$i++)
{
echo $rows[$rand_arr[$i]]['name'].' | '.$rows[$rand_arr[$i]]['description'].' | '.$rows[$rand_arr[$i]]['update_time'].'<br/>'
}
?>
示例运行截图:
代码如下:?ViewCode
PHP
include("conn.php")//调用数据库连接文件
echo
"<table
width=572
height=56
border=0
cellspacing=1>
"
//创建html表格
echo
"<tr
bgcolor=#9999FF>"
echo
"<th
width=33
scope=col>id</th>"
echo
"<th
width=100
scope=col>user_name</th>
"
echo
"<th
width=100
scope=col>user_pass</th>
"
echo
"<th
width=100
scope=col>staus</th>"
echo
"<th
width=100
scope=col>insert_time</th>"
echo
"</tr>"
$SQL
=
"select
*
from
user_info"
$query
=
mysql_query($SQL)
//SQL查询语句
while
($row
=
mysql_fetch_array($query)){
//使用while循环mysql_fetch_array()并将数据返回数组
echo
"<tr
onmouseout=this.style.backgroundColor=''
onMouseOver=this.style.backgroundColor='#99CC33'
bgcolor=#CCCCCC>"
echo
"<td>$row[0]</td>"
//输出数组中数据
echo
"<td>$row[1]</td>"
echo
"<td>$row[2]</td>"
echo
"<td>$row[3]</td>"
echo
"<td>$row[4]</td>"
echo
"</tr>"
}
echo
"</table>"输出记录截图
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)