0

Hy I have code below, I wanna return value array with function :

    <?php

include "config/koneksi.php";

//script1
$fetch1 = mysqli_query($conn, "SELECT * FROM orders_temp");

$array = array();
while($row = mysqli_fetch_assoc($fetch1)){
    $array[] = $row[id_orders_temp];
}
echo "script1: ";
print_r($array);

echo "<br>";

//script2
function cart(){
    $array1= array();

    $fetch2 = mysqli_query($conn,"SELECT * FROM orders_temp");

    while ($r=mysqli_fetch_assoc($fetch2)) {
        $array1[] = $r[id_orders_temp];
    }
    return $array1;
}

$cart1 = cart();
echo "script2 : ";
print_r($cart1);


?>

and the result :

script1: Array ( [0] => 150 [1] => 151 )
script2 : Array ( ) 

there's no problem if I print_r array without function, but when I used function as above, I got blank array( ). How can I get array value with function ?

Tian Tian
  • 15
  • 4

3 Answers3

0

Is the variable id_orders_temp returning a correct value ?? and if its a column of DB then u have to

$row['id_orders_temp'];
Rahim Khalid
  • 469
  • 6
  • 15
0

The variable $conn is not defined within the function, so you need to either pass it to the function or reference the globally available $conn.

Pass in $conn

include "config/koneksi.php";

function cart($conn) {
    $identifiers = array();

    $result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');

    while ($row = mysqli_fetch_assoc($result)) {
        $identifiers[] = $row['id_orders_temp'];
    }

    return $identifiers;
}

$cart = cart($conn);

var_dump($cart);

Reference global $conn

Ideally, you should limit global state (and accessing it), so I would not recommend this.

include "config/koneksi.php";

function cart() {
    global $conn;

    $identifiers = array();

    $result = mysqli_query($conn, 'SELECT id_orders_temp FROM orders_temp');

    while ($row = mysqli_fetch_assoc($result)) {
        $identifiers[] = $row['id_orders_temp'];
    }

    return $identifiers;
}

$cart = cart();

var_dump($cart);

Note I have renamed variables within cart() and optimized the SQL query to select only those columns actually required.

localheinz
  • 9,179
  • 2
  • 33
  • 44
-1

You have to assign the array as a global array because of the scoping inside the array, so replace the first line inside the function with one below: $array1 = global $array;

S3FaQ El
  • 3
  • 3