user3322610
user3322610

Reputation: 39

MYSQL printing a database record array

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);

I have the function above me to retrieve db records to and print it out by calling the function. But it is only printing 1 recording but I have multiple records with same ordercode and pendingorderstatus.

Upvotes: 1

Views: 69

Answers (2)

You need to return your $a at the end

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

That is because... You are getting a single row is since you are returning the $a in the first iteration itself.

Upvotes: 2

John Conde
John Conde

Reputation: 219824

You need to move your return statement outside of your loop. Once that return statement is reached your function call ends thus terminating your loop.

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

To further improve upon your function, your function will throw a E_NOTICE error because you are not defining $a before using it. To solve this just define $a to be an empty string at the top of your function. You can also move the return statement to the end of the array so your function always returns an array, even if it is empty.

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

Upvotes: 0

Related Questions