문제

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