What is the process for fetching data from a MySQL database using JavaScript after submitting input fields in PHP?
To fetch data from a MySQL database using JavaScript after submitting input fields in PHP, you can use AJAX to send a request to a PHP script that will query the database and return the results. The PHP script will receive the input fields via POST or GET parameters, execute the database query, and return the data as a JSON response. The JavaScript code will then handle the AJAX response and update the webpage with the fetched data.
<?php
// PHP script to fetch data from MySQL database based on input fields
$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 input field values
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
// Query database
$sql = "SELECT * FROM table WHERE column1 = '$input1' AND column2 = '$input2'";
$result = $conn->query($sql);
// Fetch data
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// Return data as JSON
echo json_encode($data);
// Close connection
$conn->close();
?>
Keywords
Related Questions
- What is the best way to filter out values from one table that are not present in another table in PHP?
- How can external constant definitions impact the functionality and readability of PHP classes?
- What are the best practices for handling file uploads and image manipulation in PHP, especially in relation to FTP functions?