How would I simplify this little code????

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
flashlevel
Forum Newbie
Posts: 1
Joined: Wed May 01, 2002 11:47 am

How would I simplify this little code????

Post by flashlevel »

while ($row = mysql_fetch_array($result)) {

$button1 = $row['button1'];
$button2 = $row['button2'];
$button3 = $row['button3'];
$button4 = $row['button4'];
$button5 = $row['button5'];
$button6 = $row['button6'];
$button7 = $row['button7'];
$button8 = $row['button8'];
$button9 = $row['button9'];
$button10 = $row['button10'];
$button11 = $row['button11'];
$button12 = $row['button12'];
$button13 = $row['button13'];
$button14 = $row['button14'];

}



thanks.!
johndoe110479
Forum Newbie
Posts: 1
Joined: Wed May 01, 2002 12:44 pm
Location: Bucharest, Romania
Contact:

Post by johndoe110479 »

Try this:

Code: Select all

<?
$variable_start="button";
while ($row = mysql_fetch_array($result))
&#123; 
  for($i=1; $i<=14; $i++)
      &#123;
        $variable_name=$variable_start.$i;
        $$variable_name=$row&#1111;$variable_name];
      &#125;
&#125; 
?>
DSM
Forum Contributor
Posts: 101
Joined: Thu May 02, 2002 11:51 am
Location: New Mexico, USA

Post by DSM »

A more generic code which will work with just about anything.

Code: Select all

<? 
$sql = mysql_query("SELECT * FROM tbl_name");
$rows = mysql_fetch_array($sql);

$variable_start="button"; 
$count = count($rows)

  for($i=1; $i<=$count; $i++) 
      &#123; 
        $variable_name=$variable_start.$i; 
        $$variable_name=$row&#1111;$variable_name]; 
      &#125; 

?>
The $count function allows for unlimited number of buttons without having to recode the for loop eac htime you add a button.
User avatar
sam
Forum Contributor
Posts: 217
Joined: Thu Apr 18, 2002 11:11 pm
Location: Northern California
Contact:

Post by sam »

Simplify it a little more and make it WORK :mrgreen:

Code: Select all

$i=0;
# Using a loop at this point will not work as you want it to. 
# Every iteration of the loop you will lose the last row's data
$row = mysql_fetch_array($result);
$keys = array_keys($row);
foreach($keys as $key)&#123;
     $$key = $row&#1111;$key];
&#125;
Cheers Sam :mrgreen:
User avatar
sam
Forum Contributor
Posts: 217
Joined: Thu Apr 18, 2002 11:11 pm
Location: Northern California
Contact:

Post by sam »

By the way that $I=0; is suppost to be there :)

Cheers Moe :mrgreen:
Post Reply