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! Quote 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. Quote 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? :-\ Quote 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>"; } Quote 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
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.