0% found this document useful (0 votes)
30 views10 pages

Connection - PHP: (You May Also Read)

This tutorial explains how to import data from an Excel sheet into a MySQL database using PHP. It provides a step-by-step guide, including code snippets for creating a connection to the database, uploading a CSV file, and inserting the data into the database. The document also emphasizes the importance of ensuring the CSV format matches the database structure for successful data import.

Uploaded by

henokgetnet0909
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views10 pages

Connection - PHP: (You May Also Read)

This tutorial explains how to import data from an Excel sheet into a MySQL database using PHP. It provides a step-by-step guide, including code snippets for creating a connection to the database, uploading a CSV file, and inserting the data into the database. The document also emphasizes the importance of ensuring the CSV format matches the database structure for successful data import.

Uploaded by

henokgetnet0909
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

11In this tutorial we will learn how to “Import Excel Sheet Data in MySQL

Database using PHP. When we develop some database linked website where
we have to enter data in database, sometime we have to upload bulk data in
database. If we insert data one by one it will be very difficult and time
consuming. Here You will learn how to insert bulk of data in database from
excel sheet in a couple of minutes.
This script will import data from .csv file, so save your excel sheet in .csv file.
The code is very simple we have two file here

1. index.php
2. connection.php
connection.php contain our MySQL connection detail that is localhost,
username, password and obviously database name.

1 $hostname = "localhost";
2 $username = "root";
3 $password = "";
4 $database = "test";
5
6
7 $conn = mysql_connect("$hostname","$username","$password") or die(mysql_error());
8 mysql_select_db("$database", $conn);
index.php, it contain simple form to let user to upload file and some PHP
code to insert that data in our MySQL database. So lets have a view on our
index.php file
(You may also read: Export MySQL Table Data into Excel Sheet Format in
PHP)
HTML form:

1 <form name="import" method="post" enctype="multipart/form-data">


2 <input type="file" name="file" /><br />
3 <input type="submit" name="submit" value="Submit" />
4 </form>
Please make sure that you have added enctype=”multipart/form-data”
attribute in your form tag. So it can handle file uploading.

Here is our PHP code:


1
2
3
4
5
6 if(isset($_POST["submit"]))
7 {
8 $file = $_FILES['file']['tmp_name'];
9 $handle = fopen($file, "r");
1 $c = 0;
0 while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
1 {
1 $name = $filesop[0];
1 $email = $filesop[1];
2
1 $sql = mysql_query("INSERT INTO csv (name, email) VALUES ('$name','$email')");
3 }
1
4 if($sql){
1 echo "You database has imported successfully";
5 }else{
1 echo "Sorry! There is some problem.";
6 }
1 }
7
1
8
1
9
In my case I have a database “test” and a table “csv”, csv table have three
fields id, name and email. You can use your existing database and configure
your query in above code and the important thing to note is that when you
are making .csv file make it according to your MySQL database pattern. For
example if you have name first in your query then make first column of excel
sheet for name and up-to soon.

OK there is one question that how we can get the column address of excel
sheet or .csv file. We are getting our data in form of an array. Then obviously
we should have to treat it like an array (if you don’t know about array please
read it at php.net). So it will work like this.

1 $filesop[number_of_column];
$filesop is our array name and number _of_column refers to our address
of column of excel sheet. And array always start from 0 it means that the
address of 1st column of excel sheet is 0 here.
////

22 <form action="upload.php">

<input type="file" name="txtFile" id="eskal" /></br>


<input type="submit" name="Import" value="Update Database" /> </b>

upload.php:

<?php
if(isset($_POST["Import"]))
{
$host="localhost"; // Host name.
$db_user="root";
$db_password="";
$db='test'; // Database name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());

echo $filename=$_FILES["file"]["tmp_name"];
//echo $ext=substr($filename,strrpos($filename,"."),(strlen($filename)-
strrpos($filename,".")));

if($_FILES["file"]["size"] > 0)
{

$file = fopen($filename, "r");


while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
print_r($emapData);
$sql = "INSERT into import(name,address,email,password)
values('$emapData[0]','$emapData[1]')";
mysql_query($sql);
}
fclose($file);
echo "CSV File has been successfully Imported";
}
else
echo "Invalid File:Please Upload CSV File";

}
?>

333.Hello all,
I have found my solution. Now allz working perfectly fine. I am posting my full code.
upload.php:
<html>
<body style="
background-color: rgb(128, 151, 185);
">

<form action="import_file.php" method="post"


enctype="multipart/form-data">
<table>
<tr>
<td>
Filename:
</td>
<td>
<input type="file" name="file" id="file">
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" name="submit" value="Submit">
</td>
</tr>
</table>
</form>

</body>
</html>

import_file.php:

<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>";
//echo "Stored in: " . $_FILES["file"]["tmp_name"];
$a=$_FILES["file"]["tmp_name"];
//echo $a;

$connect = mysql_connect('localhost','root','');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('test',$connect);

// path where your CSV file is located


//define('CSV_PATH','C:/xampp/htdocs/');
//<!-- C:\\xampp\\htdocs -->
// Name of your CSV file
$csv_file = $a;

if (($getfile = fopen($csv_file, "r")) !== FALSE) {


$data = fgetcsv($getfile, 1000, ",");
while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
//$num = count($data);
//echo $num;
//for ($c=0; $c < $num; $c++) {
$result = $data;
$str = implode(",", $result);
$slice = explode(",", $str);

$col1 = $slice[0];
$col2 = $slice[1];
$col3 = $slice[2];
$col4 = $slice[3];

$query = "INSERT INTO persons(id, name, email ,contacts) VALUES('".


$col1."','".$col2."','".$col3."','".$col4."')";
$s=mysql_query($query, $connect );
}
}
echo "<script>alert('Record successfully
uploaded.');window.location.href='edit_table.php';</script>";
//echo "File data successfully imported to database!!";
mysql_close($connect);
}
?>

33Dear,
I need help, how to import my Excel file into Mysql Database. I can successfully
upload excel file but its not correctly formated uploaded or imported. please
check this image,

My HTML Form looks like,

1. <form enctype="multipart/form-data" method="post" role="form">


2. <div class="form-group">
3. <label for="exampleInputFile">File
Upload</label>
4. <input type="file" name="file"
id="file" size="150">
5. <p class="help-block">
6. Only Excel/CSV File Import.
7. </p>
8. </div>
9. <button type="submit" class="btn btn-default"
name="Import" value="Import">Upload</button>
10. </form>

And my PHP code as like, I used PHP function fgetcsv()

1. <?php
2. if(isset($_POST["Import"]))
3. {
4. //First we need to make a connection with the database
5. $host='localhost'; // Host Name.
6. $db_user= 'root'; //User Name
7. $db_password= '';
8. $db= 'product_record'; // Database Name.
9.
10. $conn=mysql_connect($host,$db_user,$db_password) or die
(mysql_error());
11. mysql_select_db($db) or die (mysql_error());
12.
13. echo $filename=$_FILES["file"]["tmp_name"];
14. if($_FILES["file"]["size"] > 0)
15. {
16.
17. $file = fopen($filename, "r");
18. //$sql_data = "SELECT * FROM prod_list_1 ";
19. while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
20.
21. {
22. //print_r($emapData);
23. //exit();
24.
25. $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason)
values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
26. mysql_query($sql);
27. }
28. fclose($file);
29. echo 'CSV File has been successfully Imported';
30. header('Location: index.php');
31. }
32. else
33. echo 'Invalid File:Please Upload CSV File';
34.
35. }
36. ?>

My Excel file as like,

1. **Bench No | Product Name | Product Price | Reason**


2. ------------------------------------------------
3. CS-102 | Baby Shop | 12$ | Expired date Failed
I want only import 2nd row values into my table. Please help me how can i solve
it or give me any resource.

44database Details:
database name => phpgang
table name => excel

db.sql

Database file run in your MySQL to create database and add data in table.

1 CREATE TABLE `excel` (


2 `id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
3 `eid` VARCHAR( 100 ) NOT NULL ,
4 `name` VARCHAR( 200 ) NOT NULL ,
5 `email` VARCHAR( 200 ) NOT NULL ,
6 `dob` VARCHAR( 40 ) NOT NULL
7 ) ENGINE = MYISAM ;

db.php

Edit this file as per your database credentials.

1 <?php
2 define('DB_SERVER', 'localhost');
3 define('DB_USERNAME', 'username');
4 define('DB_PASSWORD', 'password');
5 define('DB_DATABASE', 'database');
6 $connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
7 ?>

index.php

Contains HTML and PHP include library and insert records in database.
PHP

1 <?php
2
3 ini_set("display_errors",1);
4 require_once 'excel_reader2.php';
5 require_once 'db.php';
6
7 $data = new Spreadsheet_Excel_Reader("example.xls");
8
9 echo "Total Sheets in this xls file: ".count($data->sheets)."<br /><br />";
1
0 $html="<table border='1'>";
1 for($i=0;$i<count($data->sheets);$i++) // Loop to get all sheets in a file.
1 {
1 if(count($data->sheets[$i][cells])>0) // checking sheet not empty
2 {
1 echo "Sheet $i:<br /><br />Total rows in sheet $i ".count($data->sheets[$i]
3 [cells])."<br />";
1 for($j=1;$j<=count($data->sheets[$i][cells]);$j++) // loop used to get each row of
4 the sheet
1 {
5 $html.="<tr>";
1 for($k=1;$k<=count($data->sheets[$i][cells][$j]);$k++) // This loop is
6 created to get data in a table format.
1 {
7 $html.="<td>";
1 $html.=$data->sheets[$i][cells][$j][$k];
8 $html.="</td>";
1 }
9 $eid = mysqli_real_escape_string($connection,$data->sheets[$i][cells][$j]
2 [1]);
0 $name = mysqli_real_escape_string($connection,$data->sheets[$i][cells][$j]
2 [2]);
1 $email = mysqli_real_escape_string($connection,$data->sheets[$i][cells][$j]
2 [3]);
2 $dob = mysqli_real_escape_string($connection,$data->sheets[$i][cells][$j]
2 [4]);
3 $query = "insert into excel(eid,name,email,dob) values('".$eid."','".
2 $name."','".$email."','".$dob."')";
4
2 mysqli_query($connection,$query);
5 $html.="</tr>";
2 }
6 }
2
7 }
2
8 $html.="</table>";
2 echo $html;
9 echo "<br />Data Inserted in dababase";
3 ?>
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2

66 <?php
require 'Classes/PHPExcel/IOFactory.php';

// Mysql database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";

$inputfilename = 'example_file.xlsx';
$exceldata = array();

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Read your Excel workbook


try
{
$inputfiletype = PHPExcel_IOFactory::identify($inputfilename);
$objReader = PHPExcel_IOFactory::createReader($inputfiletype);
$objPHPExcel = $objReader->load($inputfilename);
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputfilename,PATHINFO_BASENAME).'": '.$e->getMessage());
}

// Get worksheet dimensions


$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();

// Loop through each row of the worksheet in turn


for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);

// Insert row data array into your database of choice here


$sql = "INSERT INTO users (firstname, lastname, email)
VALUES ('".$rowData[0][0]."', '".$rowData[0][1]."', '".$rowData[0][2]."')";

if (mysqli_query($conn, $sql)) {
$exceldata[] = $rowData[0];
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}

// Print excel data


echo "<table>";
foreach ($exceldata as $index => $excelraw)
{
echo "<tr>";
foreach ($excelraw as $excelcolumn)
{
echo "<td>".$excelcolumn."</td>";
}
echo "</tr>";
}
echo "</table>";

mysqli_close($conn);
?>

You might also like