Page 1 of 1

Tip: Variable Variable And MySQL Queries

Posted: Wed Aug 18, 2010 4:54 am
by JakeJ
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.

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."')");
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.

Re: Tip: Variable Variable And MySQL Queries

Posted: Wed Aug 18, 2010 7:00 am
by Weirdan
why wouldn't you just use an array?

Re: Tip: Variable Variable And MySQL Queries

Posted: Wed Aug 18, 2010 7:02 am
by JakeJ
For the example above that would make sense, but for my actual application, it's not convenient.

Re: Tip: Variable Variable And MySQL Queries

Posted: Wed Aug 18, 2010 7:16 am
by requinix
Your argument is that you use variable variables because it's more convenient than arrays? That's it?


Rather than come across as trolling, I'll edit with this:
"Well yeah, it would make sense for me to drive really fast so I can get where I'm going sooner, but that's not a good reason for doing it."
Apparently I want to be here simply to have fun arguing with someone so I'll not.

Re: Tip: Variable Variable And MySQL Queries

Posted: Wed Aug 18, 2010 7:18 am
by JakeJ
It's not an argument, it's a reason. In the case of my particular app, it just made more sense to me to do it that way.