Skip to content
  • Github
  • Facebook
  • twitter
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Site Map

XpertPhp

Expertphp Is The Best Tutorial For Beginners

  • Home
  • Javascript
    • Jquery
    • React JS
    • Angularjs
    • Angular
    • Nodejs
  • Codeigniter
  • Laravel
  • Contact Us
  • About Us
  • Live Demos
How to import and export CSV files using PHP and MySQL

How to import and export CSV files using PHP and MySQL

Posted on August 29, 2019December 17, 2022 By XpertPhp 3 Comments on How to import and export CSV files using PHP and MySQL

Today, In this tutorial, we will be explaining how to import and export CSV files using PHP and MySQL. so let’s discuss Import and export CSV file.

It’s also very helpful in such as if you want to backup of data and you have data of CSV file then you can import the data into the database.

CSV extension stands for “Comma Separated Values” and contains all data in comma-separated. Normally, we have large data and need to import data into the database that time we use the following file types.

index.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<!DOCTYPE html>
<html lang="en">
<head>
  <title>How to Import and Export CSV files using PHP and MySQL - XpertPhp</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
 
<div class="container" style="margin-top:50px;">
  <div class="row">
<div class="col-lg-10"><h2>Import and export csv file</h2></div>
<div class="col-lg-1"><a href="export.php" class="btn btn-success btn-sm">Export</a></div>
<div class="col-lg-1"><button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#importModal">Import</button></div>
  </div>  
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Id</th>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Phone</th>
        <th>Created</th>
      </tr>
    </thead>
    <tbody>
<?php
include('connection.php');
$sql = 'SELECT * FROM users ORDER BY id desc';
    $result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)) {
?>
      <tr>
        <td><?php echo $row['id'];?></td>
        <td><?php echo $row['first_name'];?></td>
        <td><?php echo $row['last_name'];?></td>
        <td><?php echo $row['email'];?></td>
        <td><?php echo $row['phone'];?></td>
        <td><?php echo $row['created'];?></td>
      </tr>
<?php
} ?>
    </tbody>
  </table>
</div>
 
<!-- Modal -->
  <div class="modal fade" id="importModal" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Upload Csv file</h4>
        </div>
        <div class="modal-body">
          <form action="import.php" method="post" enctype="multipart/form-data">
<div class="col-lg-12">
<div class="form-group">
<input type="file" name="csv_file" id="csv_file" class="filestyle" data-icon="false">
</div>
</div>
<div class="col-lg-12">
<input type="submit" value="Upload file" id="upload_btn">
</div>
  </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>
</body>
</html>
See also  laravel eloquent join query example

connection.php

PHP
1
2
3
4
5
6
7
8
9
10
11
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'csv_export_import';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
 
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
?>

export.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
// including the connection file
include('connection.php');
// set headers of csv format and force download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=users.csv');
$output = "First Name,Last Name,Email,Phone\n";
 
$sql = 'SELECT * FROM users ORDER BY id desc';
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)) {
    $output .= $row['first_name'].",".$row['last_name'].",".$row['email'].",".$row['phone']."\n";
}
echo $output;
exit;
?>

import.php

here, We will use the fopen() and fgetcsv() php function in the below file. The fgetcsv() method reads for the field in the csv formate and returns the array.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
include('connection.php');
$csv_file =  $_FILES['csv_file']['tmp_name'];
if (is_file($csv_file)) {
$input = fopen($csv_file, 'a+');
$row = fgetcsv($input, 1024, ','); // here you got the header
while ($row = fgetcsv($input, 1024, ',')) {
// insert into the database
$date = date('Y-m-d H:i:s');
$sql = 'INSERT INTO users(first_name,last_name,email,phone,created) VALUES("'.$row[0].'","'.$row[1].'","'.$row[2].'","'.$row[3].'","'.$date.'")';
mysqli_query($conn, $sql);
}
}
header('location: index.php');
?>

Php, MySql Tags:Import CSV File in PHP, PHP CSV Upload, PHP File Upload Script, php with mysql, Read CSV File in PHP

Post navigation

Previous Post: How to get last inserted id from table in Laravel
Next Post: crop with resize image using the croppie plugin

Latest Posts

  • Laravel 12 Ajax CRUD Example
  • Laravel 12 CRUD Example Tutorial
  • How to Create Dummy Data in Laravel 11
  • Laravel 11 Yajra Datatables Example
  • Laravel 11 Ajax CRUD Example
  • Laravel 11 CRUD Example Tutorial
  • Laravel 10 Ajax CRUD Example Tutorial
  • Laravel 10 CRUD Example Tutorial
  • How to disable button in React js
  • JavaScript Interview Questions and Answers

Tools

  • Compound Interest Calculator
  • Hex to RGB Color Converter
  • Pinterest Video Downloader
  • Birthday Calculator
  • Convert JSON to PHP Array Online
  • JavaScript Minifier
  • CSS Beautifier
  • CSS Minifier
  • JSON Beautifier
  • JSON Minifier

Categories

  • Ajax
  • Angular
  • Angularjs
  • Bootstrap
  • Codeigniter
  • Css
  • Htaccess
  • Interview
  • Javascript
  • Jquery
  • Laravel
  • MongoDB
  • MySql
  • Nodejs
  • Php
  • React JS
  • Shopify Api
  • Ubuntu

Tags

angular 10 tutorial angular 11 ci tutorial codeigniter 4 image upload Codeigniter 4 Tutorial codeigniter tutorial CodeIgniter tutorial for beginners codeigniter with mysql crud operation eloquent relationships file upload File Validation form validation Image Upload jQuery Ajax Form Handling jquery tutorial laravel 6 Laravel 6 Eloquent Laravel 6 Model laravel 6 relationship laravel 6 relationship eloquent Laravel 6 Routing laravel 7 Laravel 7 Eloquent laravel 7 routing laravel 7 tutorial Laravel 8 laravel 8 example laravel 8 tutorial laravel 9 example laravel 9 tutorial Laravel Framework laravel from scratch laravel social login learn jquery nodejs pagination payment gateway php with mysql react js example react js tutorial send mail validation wysiwyg editor wysiwyg html editor

Copyright © 2018 - 2025,

All Rights Reserved Powered by XpertPhp.com