简体   繁体   English

使用PHP + AJAX同时从两个MySQL表中获取数据

[英]Fetching data from two MySQL tables simlutenously with PHP + AJAX

I'm creating a search box that queries two MySQL tables and lists the results in real time. 我正在创建一个查询框,该查询框查询两个MySQL表并实时列出结果。 For now though, I have a working prototype that will query only one table. 不过,到目前为止,我有一个可以正常工作的原型,该原型只能查询一个表。 I've written the following PHP code in conjunction with JQuery and it works wonderfully: 我已经与JQuery一起编写了以下PHP代码,并且效果很好:

HTML 的HTML

<input onkeyup="search(this);" type="text">
<ol id="search-results-container"></ol>

Javascript Java脚本

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();
  }
}

and PHP 和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

?>

The details of the students table are arbitrary, except for the fact that it has a String column that lists the student's last name. students表的详细信息是任意的,除了它具有列出学生姓氏的“字符串”列之外。

My problem is that there is also a staff table which is effectively the same as students but for a different purpose. 我的问题是, 还有一个staff表,该表实际上是相同的students ,但为了不同的目的。 I'd like to query the staff table at the same time as students , but have the results separated like so: 我想在与students同时查询staff表时,将结果分开,如下所示:

<h1>Students:</h1>
<p>Student1</p>
<p>Student2</p>

<h1>Staff</h1>
<p>Staff1</p>
<p>Staff2</p>

The obvious answer would be to add another $sql statement similar to the one on Line 5 and just do both queries serially - effectively doubling the search time - but I'm concerned this will take too long. 显而易见的答案是添加另一个类似于第5行的$sql语句,并且只按顺序执行两个查询-有效地使搜索时间加倍-但我担心这将花费很长时间。 Is this a false assumption (that there will be a noticeable time difference), or is there actually a way to do both queries alongside each other? 这是一个错误的假设(会有明显的时差),还是实际上有一种方法可以同时进行两个查询? Thanks in advance! 提前致谢!

If the two tables have identical structures, or if there is a subset of columns which could be made to be the same, then a UNION query might work here: 如果两个表具有相同的结构,或者如果可以使列的子集相同,则UNION查询可能在这里起作用:

SELECT *, 0 AS type FROM students WHERE lastname LIKE ?
UNION ALL
SELECT *, 1 FROM staff WHERE lastname LIKE ?
ORDER BY type;

I removed the LIMIT clause because you don't have an ORDER BY clause, which makes using LIMIT fairly meaningless. 我删除了LIMIT子句,因为您没有ORDER BY子句,这使使用LIMIT变得毫无意义。

Note that I introduced a computed column type which the result set, when ordered by it, would place students before staff. 请注意,我介绍了一种计算列type ,结果集按其排序时会将学生放在工作人员之前。 Then, in your PHP code, you would just need a bit of logic to display the header for students and staff: 然后,在您的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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM