Tip: Variable Variable And MySQL Queries
Posted: Wed Aug 18, 2010 4:54 am
This isn't a question. I wanted to use variable variables and use them to update my database. I figured it out, but I figured someone else is going to have trouble with it too.
If you don't know about variable variables in php there are several tutorials available.
When I tried just using the double dollar sign, it ended up inserting the literal text "$$a" in to my database.
I hope this manages to help someone and if you happen to have a better way, please post it.
If you don't know about variable variables in php there are several tutorials available.
Code: Select all
$x = 1;
$a = 'var'.$x;
$$a = "Hello world";
echo $$a; //output "Hello World"
//If this was all you were doing, you would just use $var1 in your insert:
mysql_query("INSERT INTO table (field1) VALUES ('$var1')");
//more than likely though, you're using variable variables in a loop and incrementing $x so you would do this:
mysql_query("INSERT INTO table(field1) VALUES ('".$$a."')");
//notice the single quotes before and after the double quotes inside the value parentheses.
//If you want to string multiples together, do this:
....('".$$a."','".$$b."','".$$c."')");
I hope this manages to help someone and if you happen to have a better way, please post it.