How can selection from a dropdown menu be saved as a variable in PHP and stored in a database?

To save the selection from a dropdown menu as a variable in PHP and store it in a database, you can use a form with a dropdown menu and submit the selected value to a PHP script. In the PHP script, you can retrieve the selected value using the $_POST superglobal, sanitize the input to prevent SQL injection, and then insert the value into the database using prepared statements.

// HTML form with a dropdown menu
<form method="post" action="save_selection.php">
    <select name="dropdown">
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        <option value="option3">Option 3</option>
    </select>
    <input type="submit" value="Submit">
</form>

// save_selection.php
<?php
// Retrieve the selected value from the dropdown menu
$selected_value = $_POST['dropdown'];

// Sanitize the input to prevent SQL injection
$selected_value = filter_var($selected_value, FILTER_SANITIZE_STRING);

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');

// Insert the selected value into the database using prepared statements
$stmt = $pdo->prepare("INSERT INTO table_name (column_name) VALUES (:selected_value)");
$stmt->bindParam(':selected_value', $selected_value);
$stmt->execute();

echo "Selection saved successfully!";
?>