How can PHP be used to link form fields to a database and retrieve data based on user input?
To link form fields to a database and retrieve data based on user input, you can use PHP to capture the user input from the form fields, construct a SQL query based on the input, and then execute the query to retrieve the relevant data from the database.
<?php
// Assuming you have a form with input fields named 'search_term' and 'category'
$searchTerm = $_POST['search_term'];
$category = $_POST['category'];
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Construct and execute the SQL query
$sql = "SELECT * FROM table_name WHERE column_name LIKE '%$searchTerm%' AND category = '$category'";
$result = $conn->query($sql);
// Display the retrieved data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Category: " . $row["category"]. "<br>";
}
} else {
echo "No results found.";
}
// Close the database connection
$conn->close();
?>