Skip to main content

Import XLSX to PHPMYADMIN

// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'agenda';

// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);

// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);

?>

<?php
require 'classes/phpexcel.php';
require_once 'classes/phpexcel/iofactory.php';
$inputFileName  = 'database/sql/agenda.xlsx';
$inputFileType  = 'Excel2007';
$objReader      = PHPExcel_IOFactory::createReader("$inputFileType");
$objReader->setReadDataOnly(true);
$objPHPExcel    = $objReader->load("$inputFileName");
$objWorksheet   = $objPHPExcel->getActiveSheet();
$highestRow     = $objWorksheet->getHighestRow();
$highestColumn  = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);

// view in table
echo '<table>' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
    echo '<tr>' . "\n";
    for ($col = 0; $col <= $highestColumnIndex; ++$col) {
        echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
    }
    echo '</tr>' . "\n";
}
echo '</table>' . "\n";

//input to mysql
for($row = 2; $row <= $highestRow; ++$row) {
    for($col = 0; $col < $highestColumnIndex; ++$col) {  
        $rows[$col] = $objWorksheet->getCellByColumnAndRow($col, $row); 
    }
    $id   ="$rows[0]";
    $ts   ="$rows[1]";
    $pd   ="$rows[2]";

    $get_data1  = "$rows[3]";

$st = PHPExcel_Style_NumberFormat::toFormattedString($get_data1, 'YYYY-MM-DD');

    $stm  ="$rows[4]";

    $get_data2  ="$rows[5]";
$et = PHPExcel_Style_NumberFormat::toFormattedString($get_data2, 'YYYY-MM-DD');

$etm
="$rows[6]"; $g ="$rows[7]"; $w ="$rows[8]"; // Prepared Statement $stmt = $mysqli->prepare("INSERT INTO `keyin` VALUES ('$id', '$ts', '$pd', '$st', '$stm', '$et', '$etm', '$g', '$w')"); //Prepared Statement Bound$stmt->bind_param('sssssssss', $id, $ts, $pd, $st, $stm, $et, $etm, $g, $w); //Prepared Statement Executed $stmt->execute(); printf("%s Row Inserted.\n", $stmt->affected_rows); //Prepared Statement Closed $stmt->close(); // If you don't want to use prepared statement, you can use this one $mysqli->query("INSERT INTO users (Username,Email,Gender,Country) VALUES ('$rows[0]', '$rows[1]', '$rows[2]', '$rows[3]')"); } $mysqli->close();

Comments