首页 > 解决方案 > PHP、Ajax 和 MySQL 中的文本框中的自动完成

问题描述

使用自动完成文本框从 MySQL 数据库表中检索数据。我的 Ajax 编码正在检索少量数据。在我的数据库表中,我有更多的 300,000 条记录。当我使用大数据时,编码不起作用。

请提供有关检索大数据的建议。哪种方法最适合检索数据。

请参阅我的编码。它可以很好地检索少量数据

<input type="text" name="protein_name" id="protein_name">

$("#protein_name").keypress(function (e){   
   var protein_name = $("#protein_name").val(); 
    if(protein_name != "") {
        $.ajax({                    
                url: '<?php echo base_url(); ?>/index.php/Protein_Main/protien_search',
                data: {protein_name: protein_name},
                dataType: "json",
                type: "POST",
                success: function (res) {                                               
                        $("#protein_name").autocomplete({
                            source: res
                        });
                }
        });
    }   }); 

PHP 编码

$query =  $this->db->query("SELECT `Name_of_the_Protein` FROM `protein` WHERE Name_of_the_Protein Like '".$protein_name."%'");      
        $protein = $query->result();    

回声 json_encode($蛋白质);

标签: phpmysql

解决方案


自动完成需要一些东西。

  • 输入元素

<input type="text" id="nmRecipientSearch">

  • 几个本地 javascript 数组:(一个包含潜在选择列表,另一个包含与每个选择对应的数字唯一 ID)

var aryRecipientsFull=["Aaron","Adon","Andrew"];

var aryLrId=["1","2","3"];

  • 绑定到输入元素的 javascript .autocomplete 处理程序:

    $( "#nm_recipient_search" ).autocomplete({ source: aryRecipientsFull,
    select: function( event, ui ) 
    {
        var numPosition,numLrId = 0;
        //Find the index position within the array for the selected item (e.g. Adon)
        numPosition=aryRecipientsFull.indexOf(ui.item.label);
        //Set a variable to the numeric value corresponding to the selected item (e.g. 2)
        numLrId=aryLrId[numPosition];
        //Populate a hidden input field (nm_lr_id) to the numeric value
        $('#nm_lr_id').val(numLrId);
        //Set the focus to the next field once a selection has been made
        $('#nm_text').focus();
    }
    });
    

确保自动完成结果出现在其他所有内容之上的 CSS 样式:

ul.ui-autocomplete { z-index: 1100; }

有几点需要考虑:

  • 我建议开始使用静态数组以确保 UI 看起来不错
  • 如果您需要(重新)动态填充数组,那么您可能需要将 .keyup 事件绑定到搜索字段,对 PHP 页面执行 AJAX 调用,然后按照您的建议进行查询,但请确保您限制结果记录的数量(可能是 10 或 20 条记录)。只需在 SELECT 查询的末尾添加“LIMIT 20”即可实现此目的。

我希望这会有所帮助。


推荐阅读