Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a LIKE clause in a PDO prepared statement? [duplicate]

Tags:

php

mysql

pdo

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?

like image 832
Mustafa Shujaie Avatar asked Dec 12 '12 04:12

Mustafa Shujaie


People also ask

What is prepared statement and How to use prepared statement in MySQL?

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?").

What does the Prepare method of a PDO object return when called successfully?

Return Values ¶ If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns false or emits PDOException (depending on error handling).

Which method is used to execute prepared query in PDO?

To prepare and execute a single SQL statement that accepts no input parameters, use the PDO::exec or PDO::query method. Use the PDO::exec method to execute a statement that returns no result set.

Why use prepared statements?

PreparedStatement allows you to write a dynamic and parametric query. By using PreparedStatement in Java you can write parameterized SQL queries and send different parameters by using the same SQL queries which is a lot better than creating different queries.


2 Answers

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);
like image 61
Wing Lian Avatar answered Nov 16 '22 00:11

Wing Lian


try like

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

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

$ret = $prep->execute(array(':needle' => '%'.$somestring.'%'));
like image 30
NullPoiиteя Avatar answered Nov 16 '22 00:11

NullPoiиteя