How can dropdown menu selections be stored in a database using PHP?
Dropdown menu selections can be stored in a database using PHP by capturing the selected value from the dropdown menu in a form submission, then inserting it into the database using SQL queries. The selected value can be accessed using the $_POST superglobal in PHP.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Capture the selected value from the dropdown menu
$selected_value = $_POST['dropdown_menu'];
// Insert the selected value into the database
$sql = "INSERT INTO table_name (column_name) VALUES ('$selected_value')";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Keywords
Related Questions
- What are the potential reasons for special characters displaying incorrectly in PHP when reading data from a MySQL database?
- Are there any potential pitfalls to be aware of when using the duplicateStyle method in PHPExcel?
- What is the significance of using single quotes around strings in PHP MySQL queries?