本文介绍了如何使用php遍历mysql查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用此功能

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

,但是它一次又一次地显示最新行.我想遍历

but it only shows the latest row over and over again. I want to loop through all the queries from

select info, username, time from newsfeed ORDER BY time DESC LIMIT 10

按降序排列.

推荐答案

以下是使用内置的php函数(假设使用旧版mysql,但使用其他数据库后端的类似功能)的此类基本模板更高级别的库).在此示例中,错误是通过引发异常来处理的,但这只是实现错误的一种方法.

Here's the basic template for this kind of thing, using built-in php functions (assuming old-style mysql, but similar using other database back-ends, or higher-level libraries). In this example, errors are handled by throwing exceptions, but that's just one way to do it.

  1. 连接到数据库
  2. 确保连接成功
  3. 运行查询
  4. 确保查询没有由于某种原因而失败(通常是SQL语法错误).如果确实失败,请找出原因并处理该错误
  5. 检查查询是否至少返回了一行(特殊情况下通常为零行)
  6. 遍历返回的行,做您需要做的所有事情.

需要定义异常类(它们是这里唯一的非内置语法,但是您不应抛出普通的异常).

The exception classes would need to be defined (they're the only non-built-in syntax here, but you shouldn't throw plain-vanilla Exceptions).

示例代码:

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

这篇关于如何使用php遍历mysql查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 09:35
查看更多