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 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图