How can PHP loops be effectively used to iterate through form data for database insertion?
When inserting form data into a database, PHP loops can be effectively used to iterate through the form fields and prepare the data for insertion. By using a loop, you can dynamically handle varying numbers of form fields and ensure all data is processed correctly before insertion into the database.
// Assuming form data is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Loop through form data and prepare for insertion
foreach ($_POST as $key => $value) {
// Sanitize the data to prevent SQL injection
$key = $conn->real_escape_string($key);
$value = $conn->real_escape_string($value);
// Insert data into the database
$sql = "INSERT INTO table_name (column_name) VALUES ('$value')";
$result = $conn->query($sql);
if (!$result) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Close the database connection
$conn->close();
}