Jump to content

How to createa function that works during a while


CSkovholm

Recommended Posts

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!

 

 

 

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.

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>";
}

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.