Jump to content

[SOLVED] fetch_array() : must inside the loop ?


bobohob

Recommended Posts

I'm confused with the fetch_array method.  Why it doesn't work outside the loop ?

 

<?php
$mysqli = new mysqli("host", "user", "pass", "database");
$query_result = mysqli->query("SELECT acolumn FROM mytable"); // there are 5 rows.

// INSIDE THE LOOP (WORKS) :
while ($row = $query_result->fetch_array()) {
echo $row[0];
}

// OUTSIDE THE LOOP (DOESN'T WORK....WHY ???) :
$myArray = $query_result->fetch_array();
for ($i=0; $i<5; $i++) { // 5 rows.
echo $myArray[$i][0];
}
?>

 

Many thanks.

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/68011-solved-fetch_array-must-inside-the-loop/
Share on other sites

The way I do it is:

 

<?php

$result = mysql_query("SELECT * FROM table");  // Or another query

// Now, we can either use a loop:

while ($array= mysql_fetch_array($result)) {
}

// Or, we can use it outside of a loop.

$array = mysql_fetch_array($result);

?>

 

This should probably work. The values can be retrieved with  $result['cell name']

Thanks for response.

 

The way I do it is:

 

<?php

$result = mysql_query("SELECT * FROM table");  // Or another query

// Now, we can either use a loop:

while ($array= mysql_fetch_array($result)) {
}

// Or, we can use it outside of a loop.

$array = mysql_fetch_array($result);

?>

 

This should probably work. The values can be retrieved with  $result['cell name']

 

the $array (from the your last line $array = mysql_fetch_array($result);) will only contain 2 items no matter what.

 

and beside, $result['cell name'] will only get the column, not the rows.

 

fetch_array() only fetches a single row, putting the column values in an array. Same with fetch_row() and fetch_assoc(). The only differences are the way the returned array is indexed.

 

Your outside-the-loop example ...

// OUTSIDE THE LOOP (DOESN'T WORK....WHY ???) :

$myArray = $query_result->fetch_array();

for ($i=0; $i<5; $i++) { // 5 rows.

echo $myArray[$i][0];

}

 

... assumes it has returned an array of rows.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.