Search code examples
phparraysajaxlivesearch

php live search with array


I am doing a live search using AJAX and PHP on my website. I have already tried using XML and i don't like it. I need the search results to be able to be updated easily and I find it way easier to do that with a database.

So, I have this code so far:

<?php
// database connection
$query = "SELECT * FROM Questions";
$doQuery = mysql_query($query);

$searchArray = array();
$x = 0;
while($row=mysql_fetch_assoc($doQuery)) {
$searchArray[$x] = $row['title'];
$x++;
}

$q = $_GET['search'];

Now I have an array with all the titles from my questions table.

How would I go about searching my array for a string as the user types each letter. (assuming that i have a function that calls the above query using ajax on keyup event).

Or am i doing this completely wrong? I would like to use a database to get my search results. What is the best way of doing this?

thanks

AFTER EDIT: I have also already tried doing a like statement as part of $query:

$query = "SELECT * FROM Questions WHERE title LIKE '%" . $q . "%'";

I didn't like how it worked because once you went past one word the result didn't match.


Solution

  • Instead of pulling the data into an array, your best solution would be to set up an AJAX solution where your AJAX endpoint runs a LIKE query with a wildcard. Common implementations would look something like:

    $query = "SELECT * FROM Questions WHERE someCol LIKE %SOME_INJECTED_VAR%";
    

    Also, as a note, you should look at using either mysqli or PDO instead of the mysql_* functions as they are deprecated and to be removed in upcoming PHP versions.