How can PHP be used to import data from an Excel file into a MySQL database?
To import data from an Excel file into a MySQL database using PHP, you can utilize the PHPExcel library to read the Excel file and then use MySQLi to connect to the database and insert the data into the appropriate table. This process involves reading the Excel file, looping through the rows and columns to extract the data, and then executing SQL queries to insert the data into the MySQL database.
require 'PHPExcel/Classes/PHPExcel.php';
$inputFileName = 'example.xlsx';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestDataRow();
$conn = new mysqli('localhost', 'username', 'password', 'database');
for ($row = 1; $row <= $highestRow; $row++) {
$data1 = $sheet->getCell('A' . $row)->getValue();
$data2 = $sheet->getCell('B' . $row)->getValue();
$sql = "INSERT INTO table_name (column1, column2) VALUES ('$data1', '$data2')";
$conn->query($sql);
}
$conn->close();
Related Questions
- Are there any potential security risks associated with using ionCube or Zend Guard for PHP encryption?
- Are there any best practices for formatting timestamps in PHP to accommodate time zone differences?
- How does MySQL handle reserved words, and why is it important to consider this when writing SQL queries in PHP?