Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LIKE in bindParam for a MySQL PDO Query

Tags:

I've read multiple examples on how these queries should be written but I'm struggling to get this specific like to run when using bindParam

Would this be the correct way to match usernames that begin with a?

$term = "a";
$term = "'$term%'";

$sql = "SELECT username 
        FROM `user` 
        WHERE username LIKE :term 
        LIMIT 10";      

$core = Connect::getInstance();

$stmt = $core->dbh->prepare($sql);
$stmt->bindParam(':term', $term, PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetchAll();
like image 278
Dan Avatar asked Jun 17 '12 01:06

Dan


People also ask

What is the use of bindParam method of PDO statement class?

The PDOStatement::bindParam() function is an inbuilt function in PHP that is used to bind a parameter to the specified variable name. This function bound the variables, pass their value as input, and receives the output value, if any, of their associated parameter marker.

Does PDO work with MySQL?

PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.

Can I bind an array to an IN () condition?

Array Binding: As per our need, we simply need to bind the PHP array to IN() clause and to obtain this functionality, we first need to convert the given array to the form acceptable by the IN() clause, which is a job carried out by PHP implode() function.

What is the difference between bindParam and bindValue?

bindParam is a PHP inbuilt function used to bind a parameter to the specified variable name in a sql statement for access the database record. bindValue, on the other hand, is again a PHP inbuilt function used to bind the value of parameter to the specified variable name in sql statement.


1 Answers

No, you don't need the inner single quotes so just $term = "$term%";

The statement you're running now would try to match 'a%' instead of a%

bindParam will make sure that all string data is automatically properly quoted when given to the SQL statement.

like image 187
Harald Brinkhof Avatar answered Sep 18 '22 09:09

Harald Brinkhof