1

Following prepared statement returns no result if I try like search('samsung').

public function search($searchFor) {
        try{
            //connect to db
            $pdo = $this->_db->connect();
            //set up SQL and bind parameters            
            $sql = "select * from item where itemName like '%:searchfor%' or description like '%:searchfor%'";
            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(':searchfor', $searchFor, PDO::PARAM_STR);
            //execute SQL
            $rows = $this->_db->executeSQL($stmt);
            return $rows;
        }
        catch (PDOException $e)
        {
            throw $e;
        }
    }

$rows return an empty array. But if I try

select * from item where itemName like '%samsung%' or description like '%samsung%;

it returns a matched item and works as expected.

I found

$sql = "select * from item where itemName like :searchfor or description like :searchfor";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":searchfor", "%$searchFor%");

works. I had to use bindValue instead. This was a totally different issue in that the SQL was correct but I used bindParam instead of bindValue (which is the correct method), hence this is not a duplicate.

Logan Lee
  • 65
  • 1
  • 2
  • 7

2 Answers2

1

did you try to use a placeholder for the whole part of the statement?

$sql = "select * from item where itemName like :searchfor or description like :searchfor";
$stmt = $pdo->prepare($sql);
$search_string = "'%" . $searchFor . "'%";
$stmt->bindParam(':searchfor', $search_string, PDO::PARAM_STR);

Altenatively without named params:

$sql = "select * from item where itemName like ? or description like ?";
$stmt = $pdo->prepare($sql);
$search_string = "'%" . $searchFor . "'%";
$stmt->bindParam('ss', $search_string, $search_string);

As far as I remember the manual, like need to thave the whole string in the variable, not only the content to look after.

Aug

Aug
  • 11
  • 3
  • Your second `bindParam` call is wrong. This is PDO, not MySQLi. Also, you can't re-use named parameters unless `PDO::ATTR_EMULATE_PREPARES` is on – Phil Feb 22 '19 at 06:56
0

The prepared statement's placeholder tells php to treat the specific value that is passed into the placeholder, as a string. Instead of this:

$sql = "select * from item where itemName like '%:searchfor%' or 
description like '%:searchfor%'";

Do this:

$sql = "select * from item where itemName like :searchfor or 
description like :searchfor";

Then bind whole values into the placeholders:

$stmt->bindParam(':searchfor', '%yourkeyword%', PDO::PARAM_STR);
JulianT
  • 36
  • 2
  • 5