What are the potential pitfalls of using a for loop to insert data into an SQL table based on user input from an HTML form?
Potential pitfalls of using a for loop to insert data into an SQL table based on user input from an HTML form include vulnerability to SQL injection attacks if user input is not properly sanitized, inefficient performance if there are a large number of iterations, and difficulty in handling errors or rollback if one of the insert queries fails. To solve this issue, it is recommended to use prepared statements with parameterized queries to prevent SQL injection attacks and improve performance.
// Establish database connection
$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);
}
// Prepare a statement for insertion
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
// Bind parameters and execute the statement in a loop for each user input
for ($i = 0; $i < count($_POST['input_data']); $i++) {
$stmt->bind_param("ss", $_POST['input_data'][$i]['value1'], $_POST['input_data'][$i]['value2']);
$stmt->execute();
}
// Close statement and connection
$stmt->close();
$conn->close();