4

I'm trying to bind two parameters to a prepared PDO select statement. This is what I have so far:

$query = "select * from books where ? LIKE ?"; $result = $db->prepare($query); $result->bindValue(1, $searchTerm, PDO::PARAM_STR); $result->bindValue(2, "%$searchValue%", PDO::PARAM_STR); $result->execute(); $rows = $result->fetchAll(PDO::FETCH_ASSOC); print_r($rows); 

This executes successfully but I don't get any rows returned.

But when I use only 1 param

$query = "select * from books where title LIKE ?"; $result->bindValue(1, "%$searchValue%", PDO::PARAM_STR); 

I get rows returned. I've checked 1000 times for my param values and names and they are fine.

I don't understand why this doesn't work with two params. Please advice.

3
  • what is $searchTerm equal ? Commented Mar 13, 2016 at 12:30
  • 4
    You can't substitute a SQL identifier, like the name of a column, by a placeholder. Commented Mar 13, 2016 at 12:31
  • 3
    See stackoverflow.com/questions/182287/… ... you can't bind table or column names Commented Mar 13, 2016 at 12:31

1 Answer 1

5

You can not bind column names in PDO with the PARAM_STR type. Ideally, you should not be binding the columns in your query, but if you really want to do so, use the PARAM_INT data type:

$query = "select * from books where ? LIKE ?"; $result = $db->prepare($query); $result->bindValue(1, $searchTerm, PDO::PARAM_INT); $result->bindValue(2, "%$searchValue%", PDO::PARAM_STR); $result->execute(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I never expected it to be something like that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.