Skip to content
Advertisement

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]

Advertisement

Answer

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]);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement