MYSQL打印数据库记录数组

时间:2014-02-19 03:08:14

标签: php mysql arrays function

function CHECKPENDINGORDERS($con, $oc, $pos){
    if(is_resource($con)){
        $sql = "SELECT * FROM eats_orders WHERE school_code = '$oc' AND order_status = '$pos'";
        $sqlresult = mysql_query($sql);
        #$pendingorderrow = mysql_fetch_array($sqlresult);
        while($row = mysql_fetch_assoc($sqlresult)){
            $a[] = $row;
            return $a;
        }

    }
}


$checkpendingorders =  CHECKPENDINGORDERS(MYSQL_LINK, $ordercode, $pendingorderstatus);

print_r($checkpendingorders);

我有上面的函数来检索db记录并通过调用函数将其打印出来。但它只打印1个录音,但我有多个具有相同订单代码和待定订单状态的记录。

2 个答案:

答案 0 :(得分:2)

您需要在结尾处返回$a

<?php
function CHECKPENDINGORDERS($con, $oc, $pos){
    if(is_resource($con)){
        $sql = "SELECT * FROM eats_orders WHERE school_code = '$oc' AND order_status = '$pos'";
        $sqlresult = mysql_query($sql);
        #$pendingorderrow = mysql_fetch_array($sqlresult);
        while($row = mysql_fetch_assoc($sqlresult)){
            $a[] = $row;
            //return $a; //<---- Not here
        }

    }
    return $a; //<----- Here
}

那是因为......你得到的是一行,因为你在第一次迭代中返回$a

答案 1 :(得分:0)

您需要将return语句移到循环之外。一旦达到return语句,您的函数调用就会结束,从而终止循环。

    while($row = mysql_fetch_assoc($sqlresult)){
        $a[] = $row;
    }
    return $a;

为了进一步改进您的功能,您的函数将抛出E_NOTICE错误,因为在使用之前您没有定义$a。要解决此问题,只需将$a定义为函数顶部的空字符串即可。您还可以将return语句移动到数组的末尾,这样您的函数总是返回一个数组,即使它是空的。

function CHECKPENDINGORDERS($con, $oc, $pos){
    $a = array();
    if(is_resource($con)){
        $sql = "SELECT * FROM eats_orders WHERE school_code = '$oc' AND order_status = '$pos'";
        $sqlresult = mysql_query($sql);
        #$pendingorderrow = mysql_fetch_array($sqlresult);
        while($row = mysql_fetch_assoc($sqlresult)){
            $a[] = $row;
        }
    }
    return $a;
}