代码之家  ›  专栏  ›  技术社区  ›  ganjan

How do I loop through a mysql query with php

  •  2
  • ganjan  · 技术社区  · 15 年前

    I tried to use this function

            $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 回复  |  直到 9 年前
        1
  •  8
  •   timdev    15 年前

    1. 连接到数据库
    2. 确保连接成功
    3. 运行查询
    4. Make sure the query didn't fail for some reason (usually a SQL syntax error). If it did fail, find out why and handle that error
    5. 检查查询是否至少返回一行(零行通常是特殊情况)
    6. 循环返回的行,做任何需要做的事情。

    示例代码:

    <?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
        }
    }
    
        2
  •  3
  •   marc_s    9 年前

    其次,你可以这样做:

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

        3
  •  1
  •   Michael Mior    15 年前

    您需要存储 $conn-query() in a variable before entering the loop. Right now you're running the query over and over again with each iteration of the loop which will always give you the first result.

    例子

    $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>";