0

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 14x9 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?

3
  • Sorry, I am eventually going to place it into an array. Here I am just trying to view the output. Commented Feb 9, 2012 at 21:27
  • 2
    what's the reason to make requested field names conditional? Commented Feb 9, 2012 at 21:35
  • it appears that was the source of my problems. Commented Feb 9, 2012 at 21:41

1 Answer 1

1

$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

SELECT 'id','name' 
 FROM a_table_in_my_database

It's giving you exactly what you ask for,

DO NOT USE BINDA PARAMS FOR COLUMN NAMES, TABLE NAMES, ETC.... only for data values

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.