weixin_33725126 2015-02-11 02:30 采纳率: 0%
浏览 53

PHP实时搜索数组

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.

  • 写回答

1条回答 默认 最新

  • weixin_33691817 2015-02-11 02:37
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题