Behseini
Behseini

Reputation: 6320

Populating MySQLi result into a PHP indexed array

I need to load result of a mysqli select statement (single field with multiple rows) into an array like:

$post = [318,310,323]

As you can see I used the fetch_array():

$posts = [];
 .....
$stmt->bind_param("s", $sessien);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM))
       {
            array_push($posts, $row);
       }
print_r($posts );

$result->free();
$stmt->close();
$customconn->close();

but on printing r the $posts is creating something like this (looks like an array in array):

Array
(
    [0] => Array
        (
            [0] => 318
        )

    [1] => Array
        (
            [0] => 310
        )

    [2] => Array
        (
            [0] => 323
        )

)

How can I fix this to have something like:

$post = [318,310,323]

Upvotes: 1

Views: 83

Answers (3)

Dharman
Dharman

Reputation: 33238

Since PHP 8.1, this became much easier. All you have to do is call fetch_column() and collect the elements into an array.

$result = $stmt->get_result();
while($id = $result->fetch_column()) {
    $posts[] = $id;
}

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57121

As mysqli_result::fetch_array() will always return an array - even for 1 field, you need to add that field rather than the entire result to your overall result array...

$row = $result->fetch_array(MYSQLI_NUM)
array_push($posts, $row[0]);

Upvotes: 1

shawn
shawn

Reputation: 4363

You should call array_push($posts, $row[0]);

Or you can call array_column on your result.

array_column($posts, 0)

Upvotes: 1

Related Questions