Asked 6 years ago
14 Apr 2018
Views 1473
jessica

jessica posted

How to import xlsx file to MySQL Database in PHP ?

i want to import .xls or .xlsx file into Mysql with PHP .

i tried to read it with Php , file function
but i get some unusual binary garbage instead of real data . so i want to import xlsx data to MySQL Database.

is there any simple solution to
noob

noob
answered Apr 25 '23 00:00

To import an XLSX file to a MySQL database using PHP, you can follow these general steps:

1.Install a library: You'll need to install a library to read the XLSX file in PHP. One popular library is PHPExcel, which can be downloaded from the official website or installed via Composer.

2.Load the XLSX file: Once the library is installed, use the PHPExcel_IOFactory class to load the XLSX file into PHP.




require_once 'path/to/PHPExcel/Classes/PHPExcel/IOFactory.php';

$inputFileName = 'path/to/your/xlsx/file';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);

3.Extract the data: Use the getActiveSheet() method to retrieve the data from the active sheet in the XLSX file. You can then loop through the rows and columns to retrieve the data you need.


$worksheet = $objPHPExcel->getActiveSheet();

foreach ($worksheet->getRowIterator() as $row) {
  $cellIterator = $row->getCellIterator();
  $cellIterator->setIterateOnlyExistingCells(false);

  $data = array();
  foreach ($cellIterator as $cell) {
    $data[] = $cell->getValue();
  }

  // Do something with the data
}

4.Connect to the MySQL database: Use the mysqli_connect() function to connect to the MySQL database.


$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdatabasename";

$conn = mysqli_connect($servername, $username, $password, $dbname);

5.Insert the data into the MySQL database: Use the mysqli_query() function to insert the data into the MySQL database.


$sql = "INSERT INTO yourtablename (column1, column2, column3)
        VALUES ('".$data[0]."', '".$data[1]."', '".$data[2]."')";

mysqli_query($conn, $sql);

6.Close the database connection: Finally, use the mysqli_close() function to close the database connection.


mysqli_close($conn);

These are the basic steps to import an XLSX file to a MySQL database using PHP. However, keep in mind that your specific implementation may vary depending on your particular requirements.
Post Answer