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?
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 "?").
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).
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.
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.
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);
try like
$sql = 'SELECT * FROM tbl_name WHERE title Like ":needle"';
$prep = $dbh->prepare($sql);
$ret = $prep->execute(array(':needle' => '%'.$somestring.'%'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With