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

gan*_*jan 2 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>";
Run Code Online (Sandbox Code Playgroud)

但它只是一遍又一遍地显示最新的一行.我想循环遍历所有的查询

select info, username, time from newsfeed ORDER BY time DESC LIMIT 10
Run Code Online (Sandbox Code Playgroud)

按降序排列.

tim*_*dev 8

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

  1. 连接到数据库
  2. 确保连接成功
  3. 运行查询
  4. 确保查询由于某种原因没有失败(通常是SQL语法错误).如果确实失败了,找出原因并处理该错误
  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
    }
}
Run Code Online (Sandbox Code Playgroud)