Tip: Variable Variable And MySQL Queries

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
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Tip: Variable Variable And MySQL Queries

Post 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.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Tip: Variable Variable And MySQL Queries

Post by Weirdan »

why wouldn't you just use an array?
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Tip: Variable Variable And MySQL Queries

Post by JakeJ »

For the example above that would make sense, but for my actual application, it's not convenient.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Tip: Variable Variable And MySQL Queries

Post 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.
Last edited by requinix on Wed Aug 18, 2010 7:39 am, edited 3 times in total.
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Tip: Variable Variable And MySQL Queries

Post 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.
Post Reply