我是 PHP/MySQL/jQuery 的新手,我被困在一个大项目的这一块上。
编码一个实时搜索框,我想根据用户输入返回数据库中已有的姓名或电话号码。我可以通过将
$variable
更改为“姓名”或“电话”来让它只输出姓名或电话号码,但我一直无法想出一个可行的解决方案来动态地同时执行这两个操作。我已经用 if/else 使用 is_numeric()
和/或 is_nan()
进行了数小时的研究/故障排除,设置了 global
变量,以多种不同的方式重新处理查询,并进行了数小时的研究。非常感谢任何建议!
库存.php:
<?php
// Session Start
session_start();
// If the user not logged in, redirect to the login page
if (!isset($_SESSION['loggedin'])) {
header('Location: index.html');
exit;
}
//Connect to database
require_once('connection.php');
if(isset($_REQUEST["term"])){
$variable = "Name";
// Prepare a select statement
$sql = "SELECT $variable FROM vendor WHERE $variable LIKE ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_term);
// Set parameters
$param_term = $_REQUEST["term"] . '%';
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$vendresult = mysqli_stmt_get_result($stmt);
// Check number of rows in the vendresult set
if(mysqli_num_rows($vendresult) > 0){
// Fetch vendresult rows as an associative array
while($row = mysqli_fetch_array($vendresult, MYSQLI_ASSOC)){
echo "<p>" . $row["$variable"] . "</p>";
}
} else{
echo "<p>No Match Found - Vendor Setup</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// close connection
mysqli_close($conn);
?>
inventoryentry.php 的 HEAD 部分:
<script>
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var vendresultDropdown = $(this).siblings(".vendresult");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
vendresultDropdown.html(data);
});
} else{
vendresultDropdown.empty();
}
});
// Set search input value on click of vendresult item
$(document).on("click", ".vendresult p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".vendresult").empty();
});
});
</script>
inventoryentry.php 的主体部分:
<div class="search-box"><input type="text" autocomplete="off" placeholder="Vendor Lookup" /><div class="vendresult"></div></div>
代码确实有效,但不是我想要的方式。
使用
UNION
查询两列。
// Prepare a select statement
$sql = "SELECT name AS result FROM vendor WHERE name LIKE ?
UNION
SELECT phone AS result FROM vendor WHERE phone LIKE ?";
...
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_term, $param_term);
当你获取结果时,使用
$row['result']
而不是 $row[$variable]
.