質問

The idea is that the query should select the name and description of some item, in some specified language. The strings are stored in a string table simple which has a column for id and a column for each language (fx: 'us' and 'fr').

Users are able to specify which language they want through an API which means that the query have to be made using PHP's prepared statements.

The following code shows how I would have wanted it to work. The problem is that name.? and description.? wont evaluate to valid columns when the parameters is bound.

$query = $mysqli->prepare(
   'SELECT name.?, description.?
    FROM item
    JOIN string AS name ON item.nameId = name.id
    JOIN string AS description ON item.descriptionId = description.id
    WHERE item.id = ?');

$query->bind_param('ssi', $lang, $lang, $id);

I want to avoid checking in code whether the language $lang is valid before querying the database. This is to avoid having to update the code, every time a new language column is added in the database.

Is it possible to specify a column name through a prepared statement?

役に立ちましたか?

解決

It seems like the answer is no. PDO : Select using a prepared statement returns column name

To avoid having to make checks in code, a separate table can be added which contains all the languages.

Languages

(id, language)
1, "us"
2, "fr"

Strings

(id, stringId, languageID, str)

1, 4, 1, "Hello"
2, 4, 2, "Bonjour"
3, 5, 1, "Yes"
4, 5, 2, "Oui"
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top