Dynamic mysql

I’m looking to change the mysql cell retieval based on a variable:

$xyz = $row[“abc_”.$var."];

where $var is the part of the cell name i need to change.

What is the correct way of doing this?

Assuming that column exists in your result set, that would work

I’m missing the question here

I think it’s rare to need to do something like this. There’s a good chance something else is wrong, or could stand to be improved.

ok…i have a bunch of columns each named with an underscore and the lang abbr:


I have a variable of “fr” or “de”. I need to pull th ecolumn from the db, but was hoping to do it dynamicaly, rather than do if…else…statements

So use the code in your first post.


What is the problem? There is no if…else anywhere in this thread.

mmm was getting errors, will investigate, just presumed it was incorrect way of doing it!

sorted, silly errors!! sorry to waste everyone’s time :-/

You probably shouldn’t have columnname_fr, columnname_de, etc columns in your database. That sounds like a place where you should normalize and create a table where the country code is one column and the associated value for that country is another.

skyline if you don’t need to select all language variants at once you could do it like this:

$var = 'fr';
$column = 'colname_' . $var; //e.g colname_fr
$query = "SELECT $column AS my_value FROM `table`";

//execute query
   $xyz = $row['my_value'];

This uses a column alias so that the PHP code always refers to my_value (or whatever alias you choose) but the actual column selected will vary.