用php查询mysql数据库如何设置php变量的位置

y3bcpkx1  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(263)

这个问题在这里已经有答案了

在mysql中何时使用单引号、双引号和反引号(13个答案)
两年前关门了。
所以我在一个网站上为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?

9fkzdhlc

9fkzdhlc1#

//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); 
  ?>

相关问题