1

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]

3 Answers 3

1

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]);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Or you can call array_column on your result.

array_column($posts, 0)

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.