【问题标题】:search and display in form PHP JQUERY AJAX以 PHP JQUERY AJAX 形式搜索和显示
【发布时间】:2017-05-18 12:39:55
【问题描述】:

我正在尝试在 mysql 数据库中搜索表单输入值,如果输入值存在于数据库中,那么我想以相同的表单显示匹配的输入行详细信息。请帮助我猜我在我的 php 代码中做错了什么。

谢谢

index.php

  <div class="col-sm-6">
    <div class="form-group">
      <label for="campaignname">Link</label>
      <input type="text" class="form-control" id="link" name="link" placeholder="Link" required>
    </div>
  </div>

  <div class="col-sm-4">
    <div class="form-group">
      <label for="campaignname">First Name</label>
      <input type="text" class="form-control" id="suppfirstname" name="suppfirstname" placeholder="First Name" required>
     </div>
   </div>
   <div class="col-sm-4">
     <div class="form-group">
       <label for="campaignname">Last Name</label>
       <input type="text" class="form-control" id="supplastname" name="supplastname" placeholder="Last Name" required>
     </div>

Jquery 调用 Ajax

<script>
 $(document).ready(function(){
      $('#link').change(function(){  
           var link = $(this).val();
           $.ajax({  
                url:"php_action/addnewlead/getlinkdata.php",  
                method:"POST",  
                data:{link:link},
                success:function(response){  
                            $("#suppfirstname").val(response.firstname);
                            $("#supplastname").val(response.lastname);
                }  
           });  
      });
 });
</script>

getlinkdata.php

<?php 

 $connect = mysqli_connect("localhost", "root", "", "test");  
 $output = '';
 if(isset($_POST["link"]))  
 {  
      if($_POST["link"] != '')
      {  
           $sql = "SELECT * FROM customertable WHERE link = '".$_POST["link"]."'";

      }  
      else
      {  
           $sql = "SELECT * FROM customertable WHERE link = 'jesusischrist'";
           // I dont want to load any data here so used wrong code

      }
      $result = mysqli_query($connect, $sql);  
      while($row = mysqli_fetch_array($result))  
      {  
           $output = $result;
      }  
      echo $output;
 }  

【问题讨论】:

  • $output = $result; 这一行是错误的。应该是$output = $row['FIELDNAME']; 此外,如果只有 1 个结果,则不需要循环。
  • 用户如何输入数据库中存在的确切名称?您可以提供下拉列表或 jquery 自动完成
  • 在这样的查询中直接使用用户数据是非常危险的!你应该真的考虑使用PPS : Prepared Parameterized Statements。这将有助于Preventing SQL injection
  • 谢谢老学徒

标签: php jquery mysql ajax search


【解决方案1】:

首先,正如有人提到的那样,您确实应该清理输入,准备好的语句也是一个很好的实践。我在这里稍微更改了您的原始代码,因为当您知道链接丢失时没有理由查询数据库。我认为你的问题的一部分是你在最后回显你的输出,你不能回显数组元素(使用 print_r 或 var_dump)。我将响应部分包装在 JSON 编码中,以将其转换为 Javascript 可解析字符串,这样您就可以保持键/值结构完整。

<?php 
try {
    if (isset($_POST['link'] && !empty($_POST['link']) {
        $mysqli = connect();

        // Sanitize your inputs. I'm guessing link is a string?
        $link = filter_var($_POST['link'], FILTER_SANITIZE_STRING);
        // create query string for prepared statement
        $sql = "SELECT firstname, lastname FROM customertable WHERE link = ? LIMIT 1";

        // prepare statement and bind variables
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param('s', $link);
        $stmt->execute();

        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();

        sendResponse(200, $row);
    }
    sendResponse(400, ['status' => 'Link not supplied']);
} catch (\Exception $e) {
    sendResponse(500, ['status' => $e->getMessage()]);
}

/**
 * Sends JSON encoded response to client side with response http code.
 */
function sendResponse($code, $response)
{
    http_response_code($code);
    echo json_encode($response);
    exit();
}

/**
 * Handles connecting to mysql.
 *
 * @return object $connect instance of MySQLi class
 */
function connect()
{
    try {
        $connect = new \mysqli("localhost", "root", "", "test");
        return $connect;
    } catch (mysqli_sql_exception $e) {
        throw $e;
    }
}

要为此更新您的 javascript,我可能会尝试这样的事情:

jQuery(document).ready(function($){
  $('#link').on('change', function(){  
    let link = $(this).val()
    ,   jqxhr = $.post(url:"php_action/addnewlead/getlinkdata.php", { link: link }); 

    jqxhr.done((response) => {
      $("#suppfirstname").val(response.firstname);
      $("#supplastname").val(response.lastname);
    });
    jqxhr.fail((error) => { throw new Error(`${error.status}: ${error.text}`)});
  });
});

【讨论】:

    猜你喜欢
    • 2012-06-29
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2022-09-24
    • 1970-01-01
    • 2020-11-13
    相关资源
    最近更新 更多