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!

 

 

 

Link to comment
Share on other sites

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
Share on other sites

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