How can PHP handle multiple selected values for database insertion more effectively?

When handling multiple selected values for database insertion in PHP, it is more effective to use an array to store the selected values and then loop through the array to insert each value into the database individually. This approach ensures that each selected value is properly inserted into the database without any data loss or duplication.

// Assuming you have a form with a multiple select field named 'selected_values[]'
$selected_values = $_POST['selected_values'];

// Connect to your database
$pdo = new PDO("mysql:host=localhost;dbname=your_database", "username", "password");

// Prepare the SQL statement
$stmt = $pdo->prepare("INSERT INTO your_table (selected_value) VALUES (:selected_value)");

// Loop through the selected values array and insert each value into the database
foreach($selected_values as $value) {
    $stmt->bindParam(':selected_value', $value);
    $stmt->execute();
}