0

I have a database that contains the name of some buttons and icons for two languages. the table is called icons and it has 4 fields (id, abbr, lang1, lang2) where abbr is the name of the variable I want to create and if the language is set to lang1 to assign the cell lang1 to the variable.

Example of the table:

id    abbr        lang1         lang2
-----------------------------------------------   
1     air    AirConditioner    Condizionatore
2     pool   Pool              Piscina

I know that I can do that with something like that

foreach (array('wifi','fridge','air','balcony','kitchen','tv','bathroom','pool') as $varname) {
 if ($$varname==1) 
{ 
SQL Select to get the information for each field
}

But I was thinking that it will be nicer if I can do that dynamically, in case I add additional rows in the table

The desired result will be to have something like this created automatically for each row

if ($lang==lang1)
{
$air=$row['lang1'];
$pool=$row['lang1'];
}
else
{
$air=$row['lang2'];
$pool=$row['lang2'];
}

I have searched if someone faced this before, but couldn't find anything usefull for my case, so any help will be welcome.

Thanks

2 Answers 2

1

If I mean right $lang is 1 or 2, this code may help.

$language = 'lang'.$lang; // creates lang1 or lang2

$result = mysql_query("SELECT * FROM icons;");
while ($row = mysql_fetch_assoc($result))
{
    $varname = $row['abbr'];
    $$varname = $row[$language];
}
Sign up to request clarification or add additional context in comments.

5 Comments

The logic should be viceversa... I need the sql query to pull out the different rows and then if the language is 1 or 2 to create dynamically the variables.
it worked even the first time as I am doing GET for the $lang from the url. Than ks
Don't forget about the protection aginst sql injection, when you use a GET field!
what is your suggestion for a protection in that case... I am not very good with that
It is not essential if only you use the code, but without this protection your database is vulnerable on the internet. Included whole database. To avoid unauthorized operations, you must escaping string before the query. You can find more information here: en.wikipedia.org/wiki/SQL_injection
1

The simplest dynamic way I can think of is that you can query the abbr you want, then pass the $lang variable as a selector to select the column of the language you want, depending on your code you can do this:

${$row['abbr']}=$row[$lang];

1 Comment

thats fine but how am I going to create these variables for all the records in the table? I dont want to specify abbr... I want all abbr in the database to be created dinamically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.