AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to exchange data with the server without refreshing, enhancing user experience fluidity. PHP, as a mainstream server-side scripting language, is widely used in web development to handle data requests and responses.
To implement database reading through AJAX, you must first write a PHP script to handle requests and query the database. The following example shows a basic PHP database query code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get keyword sent from frontend
$keyword = $_POST['keyword'];
// Query with keyword matching
$sql = "SELECT * FROM your_table WHERE your_column LIKE '%$keyword%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output matched results
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "No matching results";
}
$conn->close();
?>
If the AJAX request fails to connect to the database, it is usually due to incorrect database credentials or inaccessible database server. Confirm the database address, username, and password are correct, and that the server is running properly.
Errors in the SQL statement will cause query failures. Carefully check SQL syntax and ensure table and field names are accurate.
Use browser developer tools to check the AJAX request status. If the response status is not 200, the request failed. Verify the request URL, method, and parameters are correct.
If the PHP script does not properly return data, the frontend cannot display matching information. Add debugging output in PHP to verify query results are correctly processed and outputted.
When combining PHP and AJAX to read database data, it is crucial to ensure the database connection is successful, SQL statements are correct, and AJAX requests are properly sent and responded to. Following the above methods helps quickly identify and resolve issues, ensuring the data matching and display feature runs smoothly.