Skip to content
Advertisement

Using LIKE statement in PHP

I am setting up a new API, I am wanting to display selected info from a Mysql database with a ‘SELECT columns WHERE column LIKE % ?’, but I’am getting error in ‘%’ symbol, where I must insert ‘%’ this symbol ?

This is my query in folder models

$query = 'SELECT 
                q.id, 
                q.id_user, 
                q.id_tag,
                q.image,
                q.title,
                q.description,
                q.like,
                q.dislike,
                q.date,
                q.status
               FROM
                '.$this->table.' as q
            WHERE
                q.title LIKE ?';

This is how i execute that

$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->like);
$stmt->execute();

And this is how I request it

$question->title = isset($_GET['title']) ? $_GET['title'] : die();

Advertisement

Answer

When using a LIKE clause with a parameterised query in a prepared statement, simply put the wildcard symbol in the param you are appending.

For example, if your query was:

SELECT * FROM table WHERE column LIKE ?;

In PHP, you would define the parameter in this way:

$stmt->bindParam(1, '%' . $this->like . '%');

Of course, you can have the ‘%’ at only the start, or only the end, or both, depending on how you want the wildcard to work:

$stmt->bindParam(1, '%' . $this->like . '%');
$stmt->bindParam(1, '%' . $this->like);
$stmt->bindParam(1, $this->like . '%');

As an aside, you can also put it into the variable:

$p = '%' . $this->like . '%';
$stmt->bindParam(1, $p);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement