2

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.

4

1 回答 1

1

最好的解决方案不是将数据拉入数组,而是设置 AJAX 解决方案,让您的 AJAX 端点运行带有通配符的 LIKE 查询。常见的实现看起来像:

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

另外,请注意,您应该考虑使用 mysqli 或 PDO 而不是 mysql_* 函数,因为它们已被弃用,并将在即将发布的 PHP 版本中删除。

于 2015-02-11T02:37:01.090 回答