我试着用这个功能
$conn = db_connect();
while ($newsfeed = $conn->query("select info, username, time from newsfeed ORDER BY time DESC LIMIT 10"))
{
(...)
echo "<p>User $newsfeed_username just registerted ".$minutes." min ago </p><br>";
Run Code Online (Sandbox Code Playgroud)
但它只是一遍又一遍地显示最新的一行.我想循环遍历所有的查询
select info, username, time from newsfeed ORDER BY time DESC LIMIT 10
Run Code Online (Sandbox Code Playgroud)
按降序排列.
这是使用内置php函数的这类东西的基本模板(假设是旧式的mysql,但使用其他数据库后端或更高级别的库类似).在这个例子中,错误是通过抛出异常来处理的,但这只是一种方法.
需要定义异常类(它们是这里唯一的非内置语法,但你不应该抛出普通的异常).
示例代码:
<?PHP
//try to connect to your database.
$conn = mysql_connect(...);
//handle errors if connection failed.
if (! $conn){
throw new Db_Connect_Error(..);
}
// (try to) run your query.
$resultset = mysql_query('SELECT ...');
//handle errors if query failed. mysql_error() will give you some handy hints.
if (! $resultset){
// probably a syntax error in your SQL,
// but could be some other error
throw new Db_Query_Exception("DB Error: " . mysql_error());
}
//so now we know we have a valid resultset
//zero-length results are usually a a special case
if (mysql_num_rows($resultset) == 0){
//do something sensible, like tell the user no records match, etc....
}else{
// our query returned at least one result. loop over results and do stuff.
while($row = mysql_fetch_assoc($resultset)){
//do something with the contents of $row
}
}
Run Code Online (Sandbox Code Playgroud)