I have a variable ($q=$_GET["q"];
) that I want to run my prepared statement with. It contains a column name of my database table.
The value of the variable comes from a dropdown list. When I run the following code the output is the exact value that was chosen in the list. So it is just a column name.
$q=$_GET["q"];
$dsn = "mysql:host=$host;port=$port;dbname=$database";
$db = new PDO($dsn, $username, $password);
$sql = "SELECT DISTINCT ? FROM repertoire";
$stmt = $db->prepare($sql);
$stmt->execute(array($q));
echo "<select>";
while ( $row = $stmt->fetchObject() ) {
echo "<option>";
echo "{$row->{$q}}";
echo "</option>";
}
echo "</select>";
However, When I change this line $sql = "SELECT DISTINCT ? FROM repertoire";
to $sql = "SELECT DISTINCT ".$q." FROM repertoire";
the I get the desired rows from the database...
I'm not so good with PHP, so I guess that my syntax is wrong somewhere.
Thank you in advance for your help.