Home  >  Article  >  Web Front-end  >  An in-depth analysis of how HTML reads the database

An in-depth analysis of how HTML reads the database

王林
王林Original
2024-04-09 12:36:02585browse

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX, and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

An in-depth analysis of how HTML reads the database

In-depth analysis of HTML and how to read the database

Foreword

In the modern Web Reading the database is crucial in the application, allowing us to extract data from the database and display it to the user. HTML itself cannot directly connect to a database, but we can use JavaScript and AJAX technology to achieve this functionality. This article takes a deep dive into how HTML reads a database via JavaScript and AJAX, and explains it with examples.

JavaScript and AJAX

JavaScript is a scripting language that can dynamically modify the content and behavior of web pages. AJAX (Asynchronous JavaScript and XML) is a technology that allows JavaScript to communicate with the server without reloading the entire page. Using AJAX, we can fetch data from the database in the background and then update the page content.

Steps

Reading the database involves the following steps:

  1. Establishing a database connection: Using JavaScript to establish to the database (such as MySQL or PostgreSQL).
  2. Send Query: Write and send SQL queries via JavaScript to get data.
  3. Processing response: Receive and parse the response from the database and extract the required data.
  4. Update page: Use JavaScript to dynamically update web page content and display data obtained from the database.

Practical case

The following is an example of using HTML, JavaScript and AJAX to read the MySQL database:

HTML

<div id="data-container"></div>

<script>
// 获取数据容器元素
const dataContainer = document.getElementById("data-container");

// 数据库连接信息
const dbHost = "localhost";
const dbName = "mydb";
const dbUser = "root";
const dbPass = "root";

// 建立数据库连接
const conn = new XMLHttpRequest();
conn.open("GET", `php/connect_db.php?host=${dbHost}&name=${dbName}&user=${dbUser}&pass=${dbPass}`);
conn.send();

// 监听数据库连接响应
conn.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    // 数据库连接成功,发送查询
    const query = "SELECT * FROM users";
    const queryRequest = new XMLHttpRequest();
    queryRequest.open("POST", `php/query_db.php?query=${query}`);
    queryRequest.send();

    // 监听查询响应
    queryRequest.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        // 查询成功,获取响应
        const data = JSON.parse(this.responseText);

        // 遍历数据并填充数据容器
        for (let i = 0; i < data.length; i++) {
          dataContainer.appendChild(document.createElement("p")).textContent = `Name: ${data[i].name}, Age: ${data[i].age}`;
        }
      }
    };
  }
};
</script>

PHP (for database connections and queries)

connect_db.php

<?php
// 数据库连接信息
$dbHost = $_GET['host'];
$dbName = $_GET['name'];
$dbUser = $_GET['user'];
$dbPass = $_GET['pass'];

// 建立数据库连接
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
if ($conn->connect_error) {
  die("数据库连接失败: " . $conn->connect_error);
}

query_db.php

<?php
include 'connect_db.php';

// 获取查询字符串
$query = $_GET['query'];

// 执行查询
$result = $conn->query($query);
if (!$result) {
  die("查询失败: " . $conn->error);
}

// 将查询结果编码为 JSON 格式
$data = json_encode($result->fetch_all(MYSQLI_ASSOC));

// 返回 JSON 数据
echo $data;

Effect

Open the HTML file containing the above code in the browser, it will automatically query the database and use AJAX from the PHP script Get the response. The data obtained from the database will be populated into the "data-container" element, and the query results will be displayed on the page in real time.

The above is the detailed content of An in-depth analysis of how HTML reads the database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn