Home  >  Article  >  Backend Development  >  How to query database data with ajax php

How to query database data with ajax php

PHPz
PHPzOriginal
2023-03-29 10:13:34602browse

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:

<html>
<head>
<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>
</head>
<body>

<form>
<select name="students" onchange="showData(this.value)">
<option value="">请选择一个学生:</option>
<option value="1">小明</option>
<option value="2">小红</option>
<option value="3">小刚</option>
</select> 
</form>
<br>
<div id="result"><b>这里会显示查询到的学生信息</b></div>

</body>
</html>

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 "</table>";

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