如何使用php循环访问mysql查询

时间:2010-06-29 05:03:53

标签: php mysql loops

我尝试使用此功能

        $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

按降序排列。

3 个答案:

答案 0 :(得分:8)

这是使用内置php函数的这类东西的基本模板(假设使用旧式mysql,但使用其他数据库后端或更高级别的库类似)。在这个例子中,错误是通过抛出异常来处理的,但这只是一种方法。

  1. 连接数据库
  2. 确保连接成功
  3. 运行查询
  4. 确保查询由于某种原因没有失败(通常是SQL语法错误)。如果确实失败了,找出原因并处理该错误
  5. 检查查询是否至少返回一行(零行通常是一种特殊情况)
  6. 循环返回的行,做你需要做的任何事情。
  7. 需要定义异常类(它们是这里唯一的非内置语法,但你不应该抛出普通的异常)。

    示例代码:

    <?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
        }
    }
    

答案 1 :(得分:3)

首先,您不希望循环查询。您想循环查询将返回的记录。

第二,你可以这样做:

$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连接。

答案 2 :(得分:1)

在进入循环之前,您需要将$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>";
相关问题