qwerty77asdf qwerty77asdf - 13 days ago 5
MySQL Question

Attempting to search a MySQL database in PHP with PDO

I am attempting to find results that resemble queries in a search for example, when someone searches "tes" I want "Test McTestFace" to come up.

I have attempted to use both LIKE and MATCH AGAINST methods and, neither seem to work. When using MATCH AGAINST, nothing comes up whereas when using LIKE, only direct matches come up.

My code for MATCH AGAINST:

if (isset($_POST['submit']))
{
$query = $db->prepare("SELECT * FROM accounts WHERE MATCH (name) AGAINST (:query)");
$query->execute(array('query' => $_POST['query']));
$result = $query->fetch();
}
print_r($result);


My code for LIKE:

if (isset($_POST['submit']))
{
$query = $db->prepare("SELECT * FROM accounts WHERE name LIKE :query");
$query->execute(array('query' => $_POST['query']));
$result = $query->fetch();
}
print_r($result);


Sorry and thank you.

Answer

If using LIKE you need to wrap the query with the wildcard % to make it work.

From the docs:

With LIKE you can use the following two wildcard characters in the pattern:

% matches any number of characters, even zero characters.

_ matches exactly one character.

i.e.

$query->execute(array('query' => '%' . $_POST['query'] . '%'));
Comments