What are the common methods for storing user-selected values from HTML select menus into a MySQL database using PHP?
When a user selects a value from an HTML select menu, we need to store that value into a MySQL database using PHP. One common method to achieve this is by sending an AJAX request to a PHP script that processes the selected value and inserts it into the database. Another method is to submit a form with the selected value to a PHP script that handles the database insertion. Both methods involve using PHP to interact with the MySQL database to store the user-selected values.
<?php
// Assuming a form with a select menu named 'selectOption'
if(isset($_POST['selectOption'])) {
$selectedValue = $_POST['selectOption'];
// Connect to MySQL database
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert selected value into database
$sql = "INSERT INTO table_name (column_name) VALUES ('$selectedValue')";
if ($conn->query($sql) === TRUE) {
echo "Value inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>