I’ve been racking my brain on this one, searching all over the place and I cannot find an answer. I’m trying to pull the data from 2 columns of a 14×9 mysql db table and place it into an array. Sounds simple right? I’m trying to use PDO because it is more secure and because I just wanted to learn how it worked. Here is the code:
$anId='id';
$aName='name';
$stmt = $dbh->prepare("SELECT :theid,:thename FROM a_table_in_my_database");
$stmt->bindParam(':theid', $anId);
$stmt->bindParam(':thename', $aName);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
print_r($row);
echo '<br />';
}
‘id’ and ‘name’ are the names of the columns from the table I am trying to select. I am expecting to get something like this:
Array ( [id] => int1 [name] => stringA )
Array ( [id] => int2 [name] => stringB )
Array ( [id] => int3 [name] => stringC )
Array ( [id] => int4 [name] => stringD )
Array ( [id] => int5 [name] => stringE )
Array ( [id] => int6 [name] => stringF )
Array ( [id] => int7 [name] => stringG )
Array ( [id] => int8 [name] => stringH )
Array ( [id] => int9 [name] => stringI )
but instead I am getting this:
Array ( [id] => id [name] => name )
Array ( [id] => id [name] => name )
Array ( [id] => id [name] => name )
Array ( [id] => id [name] => name )
Array ( [id] => id [name] => name )
Array ( [id] => id [name] => name )
Array ( [id] => id [name] => name )
Array ( [id] => id [name] => name )
Array ( [id] => id [name] => name )
It literally says ‘id’ and ‘name’ and not the values.
Any idea what is going on?
$anId and $aName are strings, and because you’re treating them as bing values, PDO is wrapping them in quotes, so your SQL is effectively
It’s giving you exactly what you ask for,
DO NOT USE BINDA PARAMS FOR COLUMN NAMES, TABLE NAMES, ETC…. only for data values