search
HomeBackend DevelopmentPHP ProblemHow to query database data with ajax php

With the development of the Internet and mobile applications, the demand for dynamic pages and real-time query data is getting higher and higher. AJAX (Asynchronous JavaScript and XML) is a technology that helps developers achieve asynchronous data transmission and dynamic page updates. This article will introduce how to use AJAX and PHP to query data from the database and present it on the front end.

First, we need to create a simple database to store data. Here we take the "students" table as an example, which contains three fields: "id", "name" and "age" to store basic information of students.

After establishing the database, we need to use PHP to connect to the database and write query statements. The following is a simple query operation code:

<?php $servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

$sql = "SELECT * FROM students";
$result = $conn->query($sql);

// 处理查询结果
if ($result->num_rows > 0) {
    // 输出每行数据
    while($row = $result->fetch_assoc()) {
        echo "学生ID: " . $row["id"]. " - 姓名: " . $row["name"]. " - 年龄: " . $row["age"]. "<br>";
    }
} else {
    echo "0 结果";
}

$conn->close();
?>

The above code uses mysqli to connect to the MySQL database, performs a simple query operation, and outputs the query results to the front-end page. In actual development, it may be necessary to customize the content to be queried, as well as operations such as filtering and sorting.

Next, we need to use AJAX technology to asynchronously request server-side data and present the results on the front-end page. The following is the code for a simple AJAX query operation:


<script>
function showData(str) {
  if (str=="") {
    document.getElementById("result").innerHTML="";
    return;
  }
  var xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("result").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","getdata.php?q="+str,true);
  xmlhttp.send();
}
</script>



 

这里会显示查询到的学生信息

The above code first defines a showData function for sending asynchronous requests and accepting data returned by the server. After selecting a student in the selection box, call the showData function and pass in the ID of the selected student as a parameter.

AJAX request uses the XMLHttpRequest object, specifies the URL address and parameters of the GET request through the open method, and sends the request through the send method. When the request returns a 200 status code, the query is successful, the onreadystatechange function is called, and the data returned by the server is used as the value of the responseText attribute to display the data on the front-end page. If the request fails, the failure status code and error information can be obtained through the status attribute.

Finally, we need to write a PHP script that accepts query requests and queries data from the database. The following is the code of a simple PHP script:

<?php $q = $_GET[&#39;q&#39;];

$con = mysqli_connect(&#39;localhost&#39;,&#39;username&#39;,&#39;password&#39;,&#39;myDB&#39;);
if (!$con) {
  die(&#39;Could not connect: &#39; . mysqli_error($con));
}

mysqli_select_db($con,"students");
$sql="SELECT * FROM students WHERE id = &#39;".$q."&#39;";

$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
  echo "<td>" . $row['name'] . "</td>";
  echo "<td>" . $row['age'] . "</td>";
  echo "</tr>";
}
echo "";

mysqli_close($con);
?>

The above code first reads the parameters passed in the AJAX request, then connects to the MySQL database, executes a query statement with where conditions, and converts the query results to Return to the front-end page in the form of an HTML table.

To sum up, the combination of AJAX and PHP to query database data and present it on the front end is a common dynamic web development requirement. By using these technologies appropriately, we can quickly implement a complete dynamic page.

The above is the detailed content of How to query database data with ajax php. 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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools