首页 > 解决方案 > 使用 php 查询 mySQL 数据库。如何将 WHERE 设置为 php var

问题描述

因此,我正在网站上为 mySQL 数据库开发搜索引擎。我希望用户能够选择他们将如何进行搜索。像这样...

$searchBy=mysqli_real_escape_string($conn, $_POST['recordType']); 
$searchText=mysqli_real_escape_string($conn, $_POST['searchText']); 

$getRecordsSQL = "SELECT * FROM weighs WHERE ID='$searchText'"; 
$recordsQuery = mysqli_query($conn,$getRecordsSQL); 

上面的代码有效,但仅用于按 ID 搜索。我怎样才能让它看起来像这样..

$searchBy=mysqli_real_escape_string($conn, $_POST['recordType']); 
$searchText=mysqli_real_escape_string($conn, $_POST['searchText']); 

$getRecordsSQL = "SELECT * FROM weighs WHERE '$searchBy'='$searchText'"; 
$recordsQuery = mysqli_query($conn,$getRecordsSQL); 

该代码不起作用,但您明白了。有没有办法格式化该查询,以便用户可以选择他们想要查看的列,也就是 WHERE?

标签: phpmysql

解决方案


 //this must be in selection for search

  <form method="post" action="#">
    <input type="text" id="searchText">
   <select id="searchBy">
    <option value="table name">table name</option>
    <option value="table name 1">table name 1</option>
    <option value="table name 2">table name 2</option>
    <option value="table name 3">table name 3</option>
    <input type="submit" id="submit">
  </select>
 </form>







<script>
//after you have to send value from from select to php with ajax or jquery
 $(document).ready(function(){
   $("#submit").on("click" ,function(){
     var searchBy= $("#searchBy").val();
     var searchText=  $("#searchText").val();

    $.ajax({
       url: 'link_page_to_php_sql.php', 
        dataType: 'text', 
        cache: false,
        contentType: false,
        processData: false,
        data: {searchBy: searchBy, searchText : searchText},
        type: 'POST',
         success: function (response) {
            //some cod here if you wont after succes 
         }
     });
   });
   });

  <?php
     //and this for sql  link_page_to_php_sql.php
   if (isset($_POST['searchBy'])){
    $searchBy = $_POST['searchBy'];
    $searchText= $_POST['searchText'];
  }
     $getRecordsSQL = "SELECT * FROM weighs WHERE '$searchBy'='$searchText'"; 
     $recordsQuery = mysqli_query($conn,$getRecordsSQL); 
  ?>

推荐阅读