How can PHP for loops be used to efficiently write large amounts of data into a database?
Writing large amounts of data into a database can be efficiently done using PHP for loops. By iterating through the data and inserting it into the database within the loop, you can avoid repetitive code and streamline the process.
// Sample code to insert data into a database using a PHP for loop
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sample data array
$data = array(
array("John", "Doe"),
array("Jane", "Smith"),
array("Alice", "Johnson")
);
// Loop through the data and insert into the database
for ($i = 0; $i < count($data); $i++) {
$sql = "INSERT INTO users (first_name, last_name) VALUES ('" . $data[$i][0] . "', '" . $data[$i][1] . "')";
if ($conn->query($sql) === TRUE) {
echo "Record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Close the database connection
$conn->close();
Related questions
-
PHP CVS uploading
-
XSS SQL injection filter_var
-
PHP MySQL web server