簡體   English   中英

使用PHP + AJAX同時從兩個MySQL表中獲取數據

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

我正在創建一個查詢框,該查詢框查詢兩個MySQL表並實時列出結果。 不過,到目前為止,我有一個可以正常工作的原型,該原型只能查詢一個表。 我已經與JQuery一起編寫了以下PHP代碼,並且效果很好:

的HTML

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

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

和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 ,但為了不同的目的。 我想在與students同時查詢staff表時,將結果分開,如下所示:

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

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

顯而易見的答案是添加另一個類似於第5行的$sql語句,並且只按順序執行兩個查詢-有效地使搜索時間加倍-但我擔心這將花費很長時間。 這是一個錯誤的假設(會有明顯的時差),還是實際上有一種方法可以同時進行兩個查詢? 提前致謝!

如果兩個表具有相同的結構,或者如果可以使列的子集相同,則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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM