Are there any recommended PHP libraries or tools that can automate the process of mapping and importing specific data from a CSV file into a MySQL database?
One recommended PHP library that can automate the process of mapping and importing specific data from a CSV file into a MySQL database is "PHPExcel" which can be used to read and write Excel files. By using PHPExcel, you can easily parse the CSV file, map the columns to the corresponding database fields, and insert the data into the MySQL database.
<?php
require 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$inputFileName = 'data.csv';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
$sheet = $objPHPExcel->getActiveSheet();
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$databaseConnection = new mysqli('localhost', 'username', 'password', 'database_name');
for ($row = 1; $row <= $highestRow; $row++) {
$data = [];
for ($col = 'A'; $col <= $highestColumn; $col++) {
$data[] = $sheet->getCell($col . $row)->getValue();
}
// Map the data to database fields and insert into MySQL
$query = "INSERT INTO table_name (column1, column2, column3) VALUES ('$data[0]', '$data[1]', '$data[2]')";
$databaseConnection->query($query);
}
$databaseConnection->close();
?>
Keywords
Related Questions
- How can using the DATETIME format and NOW() function improve efficiency in handling date and time values in PHP?
- Are there any alternative methods or functions in PHP that can be used to gather server data, especially for Windows and Linux servers?
- What are the advantages of using XAMPP for PHP installation compared to other methods?