我正在创建一个查询两个MySQL表的搜索框,并实时列出结果。但就目前而言,我有一个只能查询一个表的工作原型。我已经将以下PHP代码与JQuery结合使用,并且它运行得非常好:
HTML
<input onkeyup="search(this);" type="text">
<ol id="search-results-container"></ol>
的Javascript
function search(input) {
var inputQuery = input.value;
/* $() creates a JQuery selector object, so we can use its html() method */
var resultsList = $(document.getElementById("search-results-container"));
//Check if string is empty
if (inputQuery.length > 0) {
$.get("search-query.php", {query: inputQuery}).done(function(data) {
//Show results in HTML document
resultsList.html(data);
});
}
else { //String query is empty
resultList.empty();
}
}
和PHP
<?php
include("config.php"); //database link
if(isset($_REQUEST["query"])) {
$sql = "SELECT * FROM students WHERE lastname LIKE ? LIMIT 5";
/* Creates $stmt and checks if mysqli_prepare is true */
if ($stmt = mysqli_prepare($link, $sql)) {
//Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_query);
//set parameters
$param_query = $_REQUEST["query"] . '%';
//Try and execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
$result = mysqli_stmt_get_result($stmt);
//get number of rows
$count = mysqli_num_rows($result);
if ($count > 0) {
//Fetch result rows as assoc array
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo "<h1>Students:</h1>"; //Header indicates student list
for ($i = 0; $i < $count; $i++) {
$name = $row["lastname"];
echo "<p>$name</p>";
}
}
else { //Count == 0
echo "No matches found.<br>";
}
}
else { //Execution of preped statement failed.
echo "Could not execute MySQL query.<br>";
}
} // end mysqli_prepare
} // end $_RESQUEST isset
?>
students
表的详细信息是任意的,除了它有一个列出学生姓氏的字符串列。
我的问题是还一个staff
表,它实际上与students
相同,但出于不同的目的。我想在staff
的同时查询students
表,但结果是这样分开的:
<h1>Students:</h1>
<p>Student1</p>
<p>Student2</p>
<h1>Staff</h1>
<p>Staff1</p>
<p>Staff2</p>
显而易见的答案是添加另一个类似于第5行的$sql
语句,并且只是连续地进行两个查询 - 有效地使搜索时间加倍 - 但我担心这将花费太长时间。这是一个错误的假设(会有明显的时差),还是实际上有一种方法可以同时进行两个查询?提前谢谢!
答案 0 :(得分:2)
如果两个表具有相同的结构,或者如果列的子集可以相同,则UNION
查询可能在此处起作用:
SELECT *, 0 AS type FROM students WHERE lastname LIKE ?
UNION ALL
SELECT *, 1 FROM staff WHERE lastname LIKE ?
ORDER BY type;
我删除了LIMIT
子句,因为你没有ORDER BY
子句,这使得使用LIMIT
毫无意义。
请注意,我引入了一个计算列type
,结果集在按照它排序时会将学生放在工作人员面前。然后,在您的PHP代码中,您只需要一些逻辑来显示学生和员工的标题:
$count = mysqli_num_rows($result);
$type = -1;
while ($count > 0) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$curr_type = $row["type"];
if ($type == -1) {
echo "<h1>Students:</h1>";
$type = 0;
}
else if ($type == 0 && $curr_type == 1) {
echo "<h1>Staff:</h1>";
$type = 1;
}
$name = $row["lastname"];
echo "<p>$name</p>";
--$count;
}