【问题标题】:How to get record ID from an autocomplete search using PHP and Javascript?如何使用 PHP 和 Javascript 从自动完成搜索中获取记录 ID?
【发布时间】:2021-06-05 17:41:28
【问题描述】:

我正在使用code from another thread,这让我非常接近预期的结果,但我被困在最后一步,请寻求专家的帮助。

我正在构建一个表单(带有 Xxamp 的 php),它由多个字段组成,用于将数据输入到 MySQL 数据库。自动完成输入字段正在检索文本搜索结果,但我还需要获取搜索和选择的记录的“id”值。

提交按钮需要发布所选搜索结果的 id 值 - 而不是显示的文本。

非常感谢您的帮助。

addnewrecord2.php

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Autocomplete Search Box in PHP MySQL - Php Coding Stuff</title>
 
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
 
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
  <!-- Bootstrap Css -->
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body> 

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

    <div class="container">
        <div class="row">
            <h2>Search Here</h2>
            <input type="text" name="place" id="search" placeholder="search here...." class="form-control">  
        </div>

        <div class="row">
            <input type="submit" value="Submit">
        </div>
    </div>

</form>

<script type="text/javascript">
  $(function() {
     $( "#search" ).autocomplete({
       source: 'inputnewrecord2.php',
       minLength: 3,
     });
  });
</script>


<?php

if(isset($_POST['place'])){

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // collect value of input field
    $id = $_POST['place'];

    if (empty($id)) {
        echo "Place is empty";
    } else {
        echo $id;
    }
    }
}
?>

</body>
</html>

并输入newrecord2.php

 <?php

/*
Code on this page and addrecord2.php is from: https://stackoverflow.com/questions/41104478/php-mysql-autocomplete
Same code is also here: https://www.phpcodingstuff.com/blog/autocomplete-search-box-in-php-mysql.html
*/

require_once('include/dbconn.php');

if (isset($_GET['term'])) {
     
    $query = "SELECT TowerID, Place, Place2, Dedicn FROM tbldove WHERE Place LIKE '%{$_GET['term']}%' ORDER BY Place";

     $result = mysqli_query($conn, $query);
  
     if (mysqli_num_rows($result) > 0) {
      while ($user = mysqli_fetch_array($result)) {

        if(empty($user['Place2'])){
            $placeDis = $user['Place'].", ".$user['Dedicn'];
        } else {
            $placeDis = $user['Place'].", ".$user['Place2'].", ".$user['Dedicn'];
        }

       //$res[] = $user['Place'].", ".$user['Place2'] ;

       $res[] = $placeDis;
       //$res[] = $user['TowerID'];
       //$res = [$placeDis,$user['TowerID']];
       //$res = array($placeDis,$user['TowerID']);

    }
     } else {
       $res = array();
     }
     //return json res
     echo json_encode($res);
 }

?>

【问题讨论】:

    标签: javascript php mysql forms autocomplete


    【解决方案1】:

    请考虑使用准备好的语句来防止 SQL Injections 没有它,您的数据将面临风险 在您的代码中,这是您存储数据的方式,

    $res[] = $placeDis;
    

    但您可以将其存储在另一个数组中,使用自定义键来配对 id 和地点

    $place = ['TowerID' => $user['TowerID'], 'Place' => $placeDis];
    
    $res[] = $place;
    

    在您的 JavaScript 代码中,期望返回的 JSON 被解码为对象数组

    例如,

    const res = [{
                  TowerID: 1,
                  Place: 'Nigeria'
                 }, {
                  TowerID: 2,
                  Place: 'Europe'
                }]
    

    然后您必须遍历响应,然后才能访问 Place 的 TowerID (item.TowerID) 和名称 (item.Place)

    从 PHP 文件得到的结果将是一个对象数组。因此,通过 forEach 循环,我们将能够访问数组中的每一项。

    在这种情况下,我将位置添加到 DOM 中的 span 元素中......

    results.forEach(result => {
        const elm = document.create Element('span');
        elm.id = result.TowerID;
        elm.innerText = result.Place;
    
        document.body.append(elm);
    });
    

    【讨论】:

    • 嗨@a.mola。我已经按照您的描述对数组进行了更改,但现在我在自动搜索结果中得到的只是行/空行,没有数据。我需要对 JavaScript 做些什么来获取 ID 并仍然显示文本?
    • 我已经编辑了答案,但主要思想是分配TowerID作为元素的id,然后继续使用Place作为元素的innerText。
    • 我完全明白这个概念,但我不明白如何编码。
    • 您可以将您的 JavaScript 代码添加到问题中吗?
    • 它就在那里 - 大约在第一个代码 sn-p (addnewrecord2.php) 的一半处。
    猜你喜欢
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    相关资源
    最近更新 更多