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
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']

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.