user6618037
user6618037

Reputation:

Returning more than one row with MySQLi

I am trying to make one variable ($order_description) echo 27 rows from my database using the following code:

$sql_query1 = "SELECT order_description FROM single_user_orders WHERE username = '". $_SESSION['login_user'] ."'";
$result1 = mysqli_query($dbconfig, $sql_query1);
$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
$count1 = mysqli_num_rows($result1);

if($count1 >= 1) {
    while ($row1 = $result1->fetch_assoc()) {
        $order_description = $row1['order_description'];
    }
}

Although this code is working, when I <?php echo $order_description; ?> it returns the last row of the SELECT statement and not the 27 rows I should be seeing, where am I going wrong?

Upvotes: 2

Views: 278

Answers (2)

AmmyTech
AmmyTech

Reputation: 738

use below way with group_concat and read the comments

$sql_query1 = "SELECT group_concat(order_description separator ',') as order_description FROM single_user_orders WHERE username = '". $_SESSION['login_user'] ."'" ; // update thie query with group_concat
$result1 = mysqli_query($dbconfig, $sql_query1);
$count1 = mysqli_num_rows($result1);
$order_description = array();
if($count1 >= 1) {
    while ($row1 = $result1->fetch_assoc()) {
        $order_description = explode(',',$row1['order_description']); // explode the string 
    }

}

print_r($order_description);

Upvotes: 1

Hanky Panky
Hanky Panky

Reputation: 46900

In order to see all 27 descriptions, you need to either print them within the loop or add them to an array. When you run a loop and output a single variable only after the loop has ended, it will display the last value assigned.

while ($row1 = $result1->fetch_assoc()) {
    $order_description = $row1['order_description'];
    echo $order_description."\n";
}

OR

while ($row1 = $result1->fetch_assoc()) {
    $descriptions[]=$row1['order_description'];
}
print_r($descriptions);

Note

@RiggsFolly rightly noted that you have one extra fetch_array call which gets wasted and hence you will never see the first row. Get rid of that.

Kick the third line of your code

$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);

Upvotes: 2

Related Questions