14

I have a sql query like this:

SELECT * FROM tbl_name WHERE title Like "%:needle%"

When I query the MySQL db manually with this statement it works. But when I use it with PDO and with the same values for :needle as I queried manually It just returns an empty result set.

Does utf8 encoding affects the behavior of it?

Charles
  • 50,943
  • 13
  • 104
  • 142
Mustafa Shujaie
  • 806
  • 2
  • 10
  • 18

4 Answers4

21

With PDO, this can be done like:

$stmt = $db->prepare("SELECT * FROM tbl_name WHERE title LIKE :needle");
$needle = '%somestring%';
$stmt->bindValue(':needle', $needle, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
The Codesee
  • 3,714
  • 5
  • 38
  • 78
Wing Lian
  • 2,387
  • 16
  • 14
8

try like

$sql = 'SELECT * FROM tbl_name WHERE title Like ":needle"';

$prep = $dbh->prepare($sql);

$ret = $prep->execute(array(':needle' => '%'.$somestring.'%'));
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
2

The '%' needs to be in the variable, not the statement. Put the '%' in the variable, and you should be fine.

'SELECT * FROM tbl_name WHERE title Like ":needle"'

$needle = "%$needle%"; 
ashiina
  • 996
  • 1
  • 7
  • 21
0

This worked for me:

$sql = $conn->prepare("select * from itens where nome LIKE :nome");
$nome = "%".$item->getName()."%";  
$sql->bindParam("nome",$nome);
Patronics
  • 1,351
  • 1
  • 16
  • 27
mrssolaris
  • 47
  • 9
  • 4
    Welcome to stackoverflow! To make sure your answer is helpful to others in the future, could you add a bit of a description as to why how this code solved the issue? – Patronics Nov 24 '20 at 22:09