0

I want to get the first 10 results of an array, but with the current code, it lets my one get the first one.

$query = "SELECT name FROM `table` ORDER BY `id` DESC LIMIT 10";
$result = mysqli_query($sql, $query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);

echo $row['0']; //I can do this.
echo $row['2']; // I can't do this. (It's echoing nothing).

How can I get number 1, 2,3 etc... from an array?

Thanks!

2 Answers 2

1

The function mysqli_fetch_array() only fetches one row of data, so the array you're accessing only contains the columns of that row. As you're selecting only one column, it contains only one value.

You'd have to make multiple calls to fetch_array() to access the following rows, or just use mysqli_fetch_all() instead, which returns an array of rows.

For example:

$rows = mysqli_fetch_all($result, MYSQLI_NUM);
echo $rows[0][0];
echo $rows[1][0];

Notice that you have an index for the row, and another for the column.

Sign up to request clarification or add additional context in comments.

Comments

0

Try

while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
    echo $row[0] . "<br>";
}

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.