setting variables in a while loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Smeagol
Forum Newbie
Posts: 14
Joined: Tue Jan 20, 2004 11:51 pm

setting variables in a while loop

Post by Smeagol »

Hey guys,

I have a bit of a problem.

I'd like to assign variables to equal the result of an sql query, returned in an array. for example, each time through the loop a new variable is created $variable(number 1 - 12) = the element in the returned array from the sql query.

Here's my code.

$sql = "SELECT button_text FROM ".$table." ORDER BY buttonID";
$users = mysql_query($sql);
$i = 0;
while ($user = mysql_fetch_array($users)) {
$variable(number 1 - 12) = $user["button_text"]; <--- I want to set new var here.
$i++;
}

Any thoughts or help would be appreciated.

TIA.
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

${'variable'.$i} = $user["button_text"];

Though not sure why'de you not just use an array? :o
User avatar
Smeagol
Forum Newbie
Posts: 14
Joined: Tue Jan 20, 2004 11:51 pm

Post by Smeagol »

fabulous... thank you :)

exactly what I was after.

Here's my new code.

mysql_select_db($db);
$sql = "SELECT button_text FROM ".$table." ORDER BY buttonID";
$users = mysql_query($sql);
$i = 0;
while ($user = mysql_fetch_array($users)) {
$i++;
${'button'.$i} = $user["button_text"];
}
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

i agree with mark. why not just use an array?

Code: Select all

mysql_select_db($db); 
$sql = "SELECT button_text FROM ".$table." ORDER BY buttonID"; 
$users = mysql_query($sql); 
$buttons = array();

while ($user = mysql_fetch_array($users)) 
{ 
	$buttons[] = $user['button_text']; 
}
Post Reply