What are the potential pitfalls of adding multiple rows to a table in MySQL using PHP?
One potential pitfall of adding multiple rows to a table in MySQL using PHP is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, it is important to use prepared statements with parameterized queries to safely insert data into the database.
// Sample PHP code snippet using prepared statements to insert multiple rows into a MySQL table
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare a SQL statement with placeholders for the values to be inserted
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
// Bind parameters to the placeholders
$stmt->bind_param("ss", $value1, $value2);
// Loop through an array of values to be inserted
foreach ($values_array as $row) {
$value1 = $row['value1'];
$value2 = $row['value2'];
// Execute the prepared statement for each row
$stmt->execute();
}
// Close the statement and the database connection
$stmt->close();
$conn->close();