Lerster
Lerster

Reputation: 73

PHP- Multiple variables in mysql query

I want to get the value from the Epic[2] column.

The mysql table looks like that:

ID  |  Epic[0] |  Epic[1] |  Epic[2] |  Epic[3]
-----------------------------------------------
440     xy        xy         xy           xy

I have three variables where the informations are stored.

$qualitybudget = "Epic"
$budgetType = "2"
$itemlevel = "440"

I tried the following:

$sql = "SELECT '$qualitybudget'['$budgetType'] FROM `randproppoints` WHERE id = '$itemlevel'";

Output looks like that:

SELECT 'Epic'['2'] FROM `randproppoints` WHERE id = '440'

As you see 'Epic'['2'] has the wrong syntaxing. The output for the working query should be like: Epic[2]

What is the right syntax handling in a mysql query like that?

Upvotes: 1

Views: 211

Answers (1)

andrbrue
andrbrue

Reputation: 731

Use

$sql = "SELECT `${qualitybudget}[$budgetType]` FROM `randproppoints` WHERE id = '$itemlevel'";

instead. This way, the column name is exactly formatted as you wish and encapsulated.

Note that the syntax ${xyz} has to be used to make it clear that only xyz is the name of the variable and that this is all to be printed here. Otherwise, PHP assumes it is an array and evaluates the following squared brackets for the same string insertion. Another example where this syntax has to be used is if for instance you had a variable $a = "thing"; and wanted

$b = "there are three $as";

to get "there are three things". It would not work as PHP would assume you address a variable $as, but the fix would seem like this:

$b = "there are three ${a}s";

Upvotes: 1

Related Questions