Returns multiple rows of an array from mysqli query

I have this in my functions.php file

function getUserOrders($userId){
    global $conn;
    $query = "SELECT * ";
    $query .= "FROM orders ";
    $query .= "WHERE userid=" . $userId . " ";      
    $odrset = mysqli_query($conn, $query);  

    while ($odr = mysqli_fetch_assoc($odrset)){
        return $odr;
    } 
}

What should I do in the orders.php file is to display certain fields and their values ​​from the $ odr returned array, since this fragment offers

$userId = sql_prep($_SESSION['userid']) ;
getUserOrders($userId);
echo $odr['title'].$odr['orderid'].'<br>'

I can only do this in the functions.php file ...

function getUserOrders($userId){
    global $conn;
    $query = "SELECT * ";
    $query .= "FROM orders ";
    $query .= "WHERE userid=" . $userId . " ";
    $odrset = mysqli_query($conn, $query);
    confirm_query($odrset);

    while ($odr = mysqli_fetch_assoc($odrset)){
        echo $odr['title'].$odr['orderid'].'<br>';
    } 
}

.. and call it in the orders.php file as follows:

$userId = sql_prep($_SESSION['userid']) ;
getUserOrders();

which is not very good, since I need to rework the function somewhere else and display different fields and their values. So I need $ odr to return as an array in my order.php

+4
source share
2 answers

Save it as an array, and then return the array.

function getUserOrders($userId){
    global $conn;
    $query =
      "SELECT * 
         FROM orders 
        WHERE userid= ?";    
    $odrset = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($odrset, 'i', $userId);
    mysqli_stmt_execute($odrset);

    while ($odr = mysqli_fetch_assoc($odrset)){
        $return[] = $odr;
    }
    return $return;
}

mysqli, . , http://php.net/manual/en/mysqli.quickstart.prepared-statements.php. , .

...

$orders = getUserOrders($_SESSION['userid']);
foreach($orders as $order) {
     echo $order['title'] . $order['orderid'];
}

sql_prep , , . userid , , .

+5

mysqli_fetch_assoc , :

// functions.php
function getUserOrders($userId){
    global $conn;
    $query = "SELECT * ";
    $query .= "FROM orders ";
    $query .= "WHERE userid=" . $userId . " ";      
    $odrset = mysqli_query($conn, $query);  

    $results = array();
    while ($odr = mysqli_fetch_assoc($odrset)){
        $results[] = $odr;
    }

    return $results;
}


// in your orders file
$userid = sql_prep($_SESSION['userid']);
$orders = getUserOrders($userid);

foreach ($order as $orders) {
    echo $order['title']. $order['orderid'] . '<br>';
}
0

Source: https://habr.com/ru/post/1627709/


All Articles