What are common pitfalls when using PHP to fetch data from a MySQL database and display it in a dropdown box?
One common pitfall when using PHP to fetch data from a MySQL database and display it in a dropdown box is not properly sanitizing the data retrieved from the database, which can lead to SQL injection attacks. To solve this issue, always use prepared statements to prevent SQL injection vulnerabilities.
<?php
// Establish a connection to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');
// Check for connection errors
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Prepare a query to fetch data from the database
$query = $connection->prepare("SELECT id, name FROM table");
$query->execute();
$result = $query->get_result();
// Create a dropdown box to display the fetched data
echo "<select>";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
// Close the database connection
$connection->close();
?>