我试着使用这个函数
$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按降序排列。
发布于 2010-06-29 14:42:19
这是这类事情的基本模板,使用内置的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
}
}发布于 2010-06-29 13:49:42
首先,您不希望遍历查询。您希望遍历查询将返回的记录。
第二,你可以这样做:
$conn = db_connect();
$query = mysql_query("SELECT info, username, time FROM newsfeed ORDER BY time DESC LIMIT 10");
while(($row = mysql_fetch_assoc($query)) != NULL) {
echo "<p>User {$row['username']} just registered {$minutes} min ago</p><br />";
}NB!假设这个db_connect()建立了一个mysql连接。
发布于 2010-06-29 13:04:58
在进入循环之前,您需要将$conn-query()的结果存储在一个变量中。现在,您使用循环的每次迭代一次又一次地运行查询,这将始终为您提供第一个结果。
示例
$conn = db_connect();
$result = $conn->query("select info, username, time from newsfeed ORDER BY time DESC LIMIT 10");
foreach ($result as $newsfeed)
{
(...)
echo "<p>User $newsfeed_username just registerted ".$minutes." min ago </p><br>";https://stackoverflow.com/questions/3137992
复制相似问题