bobohob Posted September 5, 2007 Share Posted September 5, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/68011-solved-fetch_array-must-inside-the-loop/ Share on other sites More sharing options...
SJames Posted September 5, 2007 Share Posted September 5, 2007 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'] Quote Link to comment https://forums.phpfreaks.com/topic/68011-solved-fetch_array-must-inside-the-loop/#findComment-341893 Share on other sites More sharing options...
bobohob Posted September 5, 2007 Author Share Posted September 5, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/68011-solved-fetch_array-must-inside-the-loop/#findComment-341908 Share on other sites More sharing options...
Barand Posted September 5, 2007 Share Posted September 5, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/68011-solved-fetch_array-must-inside-the-loop/#findComment-341920 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.