Search code examples
pdoutf-8autocompleteautosuggestutf8-decode

Make PDO powered autosuggest search box work with UTF8 data


So there is a great tutorial on making a search box with autosuggest here. And it works great on my Wordpress MySQL database.

However the problem is with Japanese characters... I added the following line to the PHP: $conn->exec("set names utf8"); Which allowed me to correctly show the Japanese results, however the search function doesn't work properly:
It just shows me all results in the whole table and not the filtered result.

Here's my full code:

if (isset($_GET['term'])){
    $return_arr = array();

    try {
        $conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD."");
        $conn->exec("set names utf8");
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $conn->prepare('SELECT supplier_company FROM wp_teleapo_supplier');
        $stmt->execute(array('term' => '%'.$_GET['term'].'%'));

        while($row = $stmt->fetch()) {
            $return_arr[] =  $row['supplier_company'];
        }

    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }


    /* Toss back results as json encoded array. */
    echo json_encode($return_arr);
}

Solution

  • Problem is in your SQL statement, you don't have where clause

    $stmt = $conn->prepare('SELECT supplier_company FROM wp_teleapo_supplier WHERE `term` LIKE ?');
    $stmt->execute(array('%'.$_GET['term'].'%'));