Page 1 of 1

Problem Creating Dynamic Variables

Posted: Wed Feb 22, 2006 11:06 am
by Toot4fun
I'm trying to create variables on the fly based on values in an array. However, I'm having some problems with the concatenation and I'm assuming that it's because I'm trying to join two variables together to create a new variable name.

Code: Select all

$colors[] = "Black";
$colors[] = "Blue";
$colors[] = "Silver";
$colors[] = "Tan";
$colors[] = "Gold";
$colors[] = "White";
$colors[] = "Red";

for($i=0; $i <= (count($colors) - 1); $i++){
     "$query" . $colors[$i] = "SELECT * FROM tblColors WHERE color='" . $colors[$i] . "'";
}
What I'd like to have is this:
$queryBlack = "SELECT * FROM tblColors WHERE color='Black'";
$queryBlue = "SELECT * FROM tblColors WHERE color='Blue'";
etc...

Is this possible? If so, how is it done, because obviously I've missed something.

Posted: Wed Feb 22, 2006 11:09 am
by s.dot

Code: Select all

foreach($colors as $color){
  mysql_query("SELECT * FROM colortbl WHERE color='$color'");
}
:?:

Posted: Wed Feb 22, 2006 11:12 am
by feyd
Is there a reason you want to have all these queries separate? It seems like they'd work much better together, performance-wise it definitely will anyways.

Posted: Wed Feb 22, 2006 11:20 am
by Toot4fun
That is a very valid question and that's my fault because my post was not correct. It should be like this:

Code: Select all

$colors[] = "Black";
$colors[] = "Blue";
$colors[] = "Silver";
$colors[] = "Tan";
$colors[] = "Gold";
$colors[] = "White";
$colors[] = "Red";

for($i=0; $i <= (count($colors) - 1); $i++){
     "$query" . $colors[$i] = "SELECT * FROM tbl" . $colors[$i];
}
Each color is a different table, so I'm trying to just run all the queries at once.

$queryBlack = "SELECT * FROM tblBlack";
$queryBlue = "SELECT * FROM tblBlue";

I apologize for the confusion.

Posted: Wed Feb 22, 2006 11:32 am
by feyd

Code: Select all

$colors = array();
$colors[] = "Black";
$colors[] = "Blue";
$colors[] = "Silver";
$colors[] = "Tan";
$colors[] = "Gold";
$colors[] = "White";
$colors[] = "Red";

foreach($colors as $color)
{
  ${'query' . $color} = 'SELECT * FROM `tbl' . $color . '`';
}
For how it works, read Variable Variables.

Posted: Wed Feb 22, 2006 12:00 pm
by Toot4fun
PERFECT! I had no idea that even existed. Thank you very much for the help.

Posted: Wed Feb 22, 2006 12:10 pm
by josh
why not use a join?