Friday, June 22, 2012

How to Dynamically Create Variables and Loop through it

So what I wanted to create was a form and the middle had 10 rows.  I wanted a way to loop through all 10 rows without having to have the same code 10 times.

I found by doing

${'foo' . $x}

creates an array that would them make the variables foo1, foo2, ... foo20.

It also works as a session/post variable -> 
$_SESSION['foo' . $x]
$_POST['foo' . $x]
Here's a snippet of code:

$item = 1;

for ($i=0; $i < $num; $i++)
$_SESSION['line' .  $item] = mysql_result($result, $i, "table1.x");
$_SESSION['line' .  $item] = mysql_result($result, $i, "table1.x");
$_SESSION['line' .  $item] = mysql_result($result, $i, "table2.x");

Now I did run into an issue with the sql insert statement. Here is how I got around it:
$sqlqueryitems = "$id', '${'line' . $item }',
                        '${'line' . $item }', 
                        '${'line' . $item }";

$sql = "INSERT INTO table_items (line1, line2, line3)
if (!mysql_query($sqlitems,$con))

die('Error: ' . mysql_error($con));