为什么查询只返回一个记录而不是多个?

时间:2013-07-15 18:36:56

标签: php mysql database arrays

我正在使用PHP和MySql。以下是我的代码:

$con=mysql_connect("localhost","XYZ","pqr") or die("Failed to connect with database!!!!");
    mysql_select_db("LMN", $con);
$sql  =" SELECT DATE_FORMAT( FROM_UNIXTIME( transaction_date ) , '%d/%m/%Y') 'date', COUNT(*) 'total count', SUM(transaction_status = 'success') ";
        $sql .=" success, SUM(transaction_status = 'inprocess') inprocess, SUM(transaction_status = 'fail') fail, ";
        $sql .=" SUM(transaction_status = 'cancelled') cancelled FROM user_transaction WHERE ";
        $sql .=" transaction_date >= 1325376000 AND transaction_date <= 1373846400 GROUP BY date(FROM_UNIXTIME(transaction_date)) ";
$r= mysql_query($sql) or die(mysql_error()); 

        $result  = mysql_fetch_array($r, MYSQL_ASSOC);
        print_r($result); 
die;

如果我在PHPMyadmin中运行上面的查询,它给了我完美的结果(即47个匹配的记录),但是当我运行PHP文件时,它只给出了我的单个记录:

Array
(
    [date] => 11/04/2012
    [total count] => 1
    [success] => 0
    [inprocess] => 0
    [fail] => 0
    [cancelled] => 1
)

实际上这是第一个匹配的记录。我可以帮助我获取PHPMyadmin中的所有匹配记录数组吗?提前谢谢。

3 个答案:

答案 0 :(得分:2)

mysql_fetch_array()通常在while循环中调用,因为当没有更多记录可供阅读时,它会返回false

要将所有记录提取到数组中:

$rows = array();
while ($row = mysql_fetch_array($result))
    $rows[] = $row;

但这通常效率很低,浪费了大量内存。如果可以,请将实际处理放在循环中。

答案 1 :(得分:0)

如果您希望获得多个结果,则应该迭代它:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo($row[0]);  //example
}

答案 2 :(得分:0)

使用此:

While($result = mysql_fetch_array($r)) {
   print_r($result);
}

阅读更多关于 mysql_fetch_array 的函数,它会逐一返回结果,因为你需要使用while:)