【问题标题】:Autocomplete in the text box in PHP, Ajax and MySQLPHP、Ajax 和 MySQL 中的文本框中的自动完成
【发布时间】:2019-08-01 09:00:18
【问题描述】:

使用自动完成文本框从 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($protein);

【问题讨论】:

  • 在这些情况下最好的方法是返回最大数量的记录(例如前 10 条记录)。也因为显示太多记录对用户不可用
  • 使用limit和offset
  • 尝试为您的问题添加更多上下文并使其更准确。还要避免陷入XY question trap - 基本上是“你在为正确的问题提出错误的问题”
  • @GiacomoM 它的自动完成文本框。
  • 最好的办法是在查询中设置限制 10

标签: php mysql


【解决方案1】:

自动完成需要一些东西。

  • 输入元素

&lt;input type="text" id="nmRecipientSearch"&gt;

  • 几个本地 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”即可实现此目的。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    相关资源
    最近更新 更多