If you want to upload a csv file have large number of records and you don’t want to use any loop statement then You can use MySQL’s LOAD DATA INFILE
statement to directly load a CSV file into a database table without using a loop in PHP. Here’s a PHP code snippet that demonstrates how to achieve this:
<?php
// Database connection parameters
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// CSV file path
$csv_file = "/path/to/your/file.csv";
// Database connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to load data from CSV into MySQL table
$sql = "LOAD DATA INFILE '$csv_file'
INTO TABLE your_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES"; // Use IGNORE 1 LINES if your CSV has a header row
// Execute the query
if ($conn->query($sql) === TRUE) {
echo "CSV data imported successfully";
} else {
echo "Error: " . $conn->error;
}
// Close connection
$conn->close();
?>
Make sure to replace your_username, your_password, your_database, your_table, and /path/to/your/file.csv with your actual database credentials, table name, and CSV file path respectively. Also, ensure that the MySQL server has the necessary permissions to read the CSV file. You may need to adjust file permissions or MySQL settings accordingly. Additionally, note that the LOAD DATA INFILE statement might be restricted by your MySQL server configuration for security reasons, so you may need to adjust server settings or consult with your database administrator.