php - 使用 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?
解决方案
//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);
?>
推荐阅读
- amazon-web-services - 断开连接后保持 AWS EC2 Windows 服务器终端应用程序处于活动状态
- c# - 图像分类中 Ml.net 中的异常
- webpack - 即使我在 webpack 中定位它,也找不到带有本机扩展的 react-native-web 模块
- javascript - Vue分隔符不在属性中工作,但在元素中工作
- php - Nginx 没有正确加载 JS、CSS
- git - git 开关保留被忽略的文件夹
- python - 你如何“连接”这个源代码和我的 tkinter python
- docker - 如何在不手动运行 dbt deps 的情况下配置 DBT 依赖项?
- python - 为什么在这个 for 循环中打印 3?
- python - pygame中的随机系统运动