dongqian9567 2012-03-29 06:23
浏览 48
已采纳

使用PHP在MySQL表中搜索自动完成框中的多个字段

Im trying to search two of the fields in my table. (Database table contains cocktail names, with their name, ingredients and description) When a user types their desired term into the search box, auto complete results are given using Ajax/jquery.

I've got it working searching one field (Name) but can't seem to get it to do more than the one(Name & Ingredients). Another problem is when the results are given (they are given as links) When you select them it puts the data in the entry box instead of taking you to the next page.

index.php:

<script>
$(document).ready(function(){
 $("#tag").autocomplete("autocomplete.php", {
        selectFirst: true
    });
});
</script>

    <label>Tag:</label>
    <input name="tag" type="text" id="tag" size="40"/>

autocomplete.php:

<?php
    $q=$_GET['q'];
    $my_data=mysql_real_escape_string($q);
    $mysqli=mysqli_connect('localhost','ignitet1','password','ignitet1_WhatCocktail') or die("Database Error");
    $sql="SELECT Name FROM tblCocktail WHERE Name LIKE '%$my_data%' ORDER BY Name";
    $result = mysqli_query($mysqli,$sql) or die(mysqli_error());

    if($result)
    {
        while($row=mysqli_fetch_array($result))
        {
            echo "<a href=\"details.php\">";
            echo $row['Name']."," , "<br />";
            echo "</a>";
        }
    }
?>

Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • dongxiao0449 2012-03-29 06:32
    关注

    I'm not sure about forcing a link to that page, but for a quick and dirty fix on the search I would add: OR Ingredients LIKE '%$my_dat%' before the ORDER clause.

    Update:

    user710502 is correct about the fields to be selected in the query. As for the autocomplete, I looked at the documentation and it looks like you will have to create a custom event handler for the autocompleteselect event. This event fires when the user chooses an option from the dropdown. The default behavior (as you know) is to fill the field with the 'value'. Your added code will look something like this:

    $("#selector-for-field").bind('autocompleteselect',function(event,ui){
        event.preventDefault(); // this will stop the field from filling
        // maybe make the value sent from the serverside a hyperlink,
        // eg. http://www.wherever.com/you/want/the/item/to/link-to
        // then in here do something like:
        window.location(ui.item.value);
    });
    

    You'll have to double check that ui.item.value works because I didn't check it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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