Search code examples
phpmysqlpdosql-like

how to bind several columns to one variable in PDO like query?


I have a variable $search and I want to search for records containing the $search in multiple columns

$query="Select * from products where name LIKE ? OR color LIKE ?"
$stmt = $this->pdo->prepare($query);
$results=$stmt->execute(array("%$search%","%$search%"));

but when I try to execute print_r($results);, I get nothing displayed except for a '1'.The problem perhaps is binding of the $search variable to the query.So I am curious whether there's a way to handle such a situation and what's the best working alternative.Thanks


Solution

  • $results is the success status of the PDOStatement execution; the returned rows are still in the $stmnt object. You need to iterate over the returned rows and print the individually.

    while ($row = $stmnt->fetch(PDO::FETCH_ASSOC)) {
        print_r($row);
    }
    

    will work.