我尝试使用这个功能
$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>";
但它只一遍又一遍地显示最新行。我想循环遍历所有查询
select info, username, time from newsfeed ORDER BY time DESC LIMIT 10
按降序排列。
这是此类事情的基本模板,使用内置的 php 函数(假设是旧式 mysql,但使用其他数据库后端或更高级别的库类似)。在此示例中,错误是通过引发异常来处理的,但这只是一种方法。
- 连接到数据库
- 确保连接成功
- 运行查询
- 确保查询没有因某种原因失败(通常是 SQL 语法错误)。如果失败,找出原因并处理该错误
- 检查查询是否至少返回一行(零行通常是一种特殊情况)
- 循环返回的行,执行您需要执行的操作。
需要定义异常类(它们是这里唯一的非内置语法,但您不应该抛出普通异常)。
示例代码:
<?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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)