How can PHP be used to compare user input with a MySQL database and display the matching entries in a browser?
To compare user input with a MySQL database and display matching entries in a browser, you can use PHP to query the database based on the user input, fetch the results, and display them on the webpage. This can be achieved by connecting to the database, executing a SELECT query with a WHERE clause to match the user input, fetching the results, and then displaying them in an HTML format on the webpage.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get user input
$user_input = $_POST['user_input'];
// Query database
$sql = "SELECT * FROM table_name WHERE column_name = '$user_input'";
$result = $conn->query($sql);
// Display matching entries
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "No matching entries found";
}
// Close database connection
$conn->close();
?>
Related Questions
- How can PHP developers ensure that the address bar remains unchanged when redirecting from one domain to another using PHP?
- How can PHP be used to alphabetically sort a list of names effectively?
- What are the considerations for embedding images in HTML using base64 encoding in PHP, and how does it affect performance and security?