CSkovholm Posted May 24, 2011 Share Posted May 24, 2011 Hey all. I'm having a little bit of an issue here. I'll start by showing the code: function dbq($sql) { $q = mysql_query($sql); $row = mysql_fetch_array($q); return $row; } $row = dbq("SELECT * FROM admin"); echo $row['username']; Above code obviously displays a function that can be used for single database outputs.. But, i wanna use it for multiple data outputs, using a while with this function. Something like: while($row = dbq("SELECT * FROM admin")) { echo $row['username']; echo "<br />"; } But it returns errors like, either does it display the first row a billion times, or does simply timeout.. How can this be done? Thanks in advance! Link to comment https://forums.phpfreaks.com/topic/237352-how-to-createa-function-that-works-during-a-while/ Share on other sites More sharing options...
Pikachu2000 Posted May 24, 2011 Share Posted May 24, 2011 In the while() loop, assign the results to a new array, then return that array. You would then do your formatting by looping through the array returned by the function. function dbq($sql) { $q = mysql_query($sql); $array = array(); while( $row = mysql_fetch_array($q) ) { $array[] = $row; } return $array; } $row = dbq("SELECT * FROM admin"); print_r($row); // This will show you the structure of the resulting multidimensional array. Link to comment https://forums.phpfreaks.com/topic/237352-how-to-createa-function-that-works-during-a-while/#findComment-1219666 Share on other sites More sharing options...
CSkovholm Posted May 24, 2011 Author Share Posted May 24, 2011 Ah, i get it now! Only how would i do the formatting of the array trough the new while? :-\ Link to comment https://forums.phpfreaks.com/topic/237352-how-to-createa-function-that-works-during-a-while/#findComment-1219668 Share on other sites More sharing options...
Pikachu2000 Posted May 24, 2011 Share Posted May 24, 2011 You would do the formatting outside of the function, preferably. Since the new array is multidimensional, each record returned will be in it's own numerically indexed element. This would be an example, assuming the query returns 3 fields called id, name, and email from each record: $row = dbq("SELECT * FROM admin"); // calls the function and assigns the returned array to $row foreach( $row as $value ) { echo "{$value['id']}<br>{$value['name']}<br>{$value['email']}<br>"; } Link to comment https://forums.phpfreaks.com/topic/237352-how-to-createa-function-that-works-during-a-while/#findComment-1219673 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.