1

I am using MYSQLI query to extract data into an array. But when printing the array content, it looks that data is being populated into sub array. This is my code:


<?php
require_once 'database.php';

// Choose the y-axis
$sql = "SELECT `O3` FROM giordan_mod ORDER BY id DESC LIMIT 4";
$resulty = mysqli_query($conn, $sql);
$datay = [];
while($row = mysqli_fetch_array($resulty, MYSQLI_NUM))
{
      $datay[] = $row;
}

echo '<pre>'; print_r($datay);'</pre>';
?>

<?php
$test = array(4, 6, 9, 15);
echo '<pre>'; print_r($test);'</pre>';
?>

But when printing the array, the result are as follows:

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

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

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

    [3] => Array
        (
            [0] => 40.28
        )

)

Array
(
    [0] => 4
    [1] => 6
    [2] => 9
    [3] => 15
)

But I would like that MYSQLI query input data into an array and not sub array. That is I need $datay array looks as $test array.

0

1 Answer 1

1

mysqli_fetch_array() returns an array representing a row of data from your SQL command. Even if you only fetch a single command, it will always be an array. To fetch fetch a single column you need to use mysqli_fetch_column().

You can use PDO instead. It is easier and offers more functionality including a method to fetch a single function.

If you are stuck with mysqli, then you can use a loop and fetch the single column yourself.

$sql = "SELECT `O3` FROM giordan_mod ORDER BY id DESC LIMIT 4";
$resulty = mysqli_query($conn, $sql);
$datay = [];
foreach($resulty as $row) {
    $datay[] = $row['O3'];
}

or even simpler:

$sql = "SELECT `O3` FROM giordan_mod ORDER BY id DESC LIMIT 4";
$resulty = mysqli_query($conn, $sql);
$datay = array_column($resulty->fetch_all(MYSQLI_ASSOC), 'O3');
Sign up to request clarification or add additional context in comments.

5 Comments

Please consolidate duplicate content.
@mickmackusa No need. It's good as it is now.
With different pieces of advice on the same topic spread across Stack Overflow? I disagree. How unfortunate that researchers will need to open more than one page to see all the viable techniques. We can serve our knowledge better than this.
@mickmackusa It's a good well-written duplicate.
The question is upvoted so it will survive as a signpost. Your advice should be evaluated and sorted on a canonical page to provide an optimal researcher experience. Your answer cannot be sorted in solitude.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.