Attempting to search a MySQL database in PHP with PDO

Question

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.


Show source
| pdo   | php   | mysql   | search   2016-11-19 12:11 2 Answers

Answers to Attempting to search a MySQL database in PHP with PDO ( 2 )

  1. 2016-11-19 13:11

    To match against wildcards, you need to use '%'.$_POST['query'].'%'. (for LIKE).

  2. 2016-11-19 13:11

    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'] . '%'));
    

Leave a reply to - Attempting to search a MySQL database in PHP with PDO

◀ Go back