You are on page 1of 8

Create a Database in MySQL

The first step in this tutorial is the creation of a MySQL database. Since Cloudways provides the custom mysql manager in
the platform which contains a database for app. you can create tables by running SQL queries. Create a
table employeeinfo in database using the following SQL query.

1 CREATE TABLE employeeinfo(


2 emp_id VARCHAR(50) UNSIGNED PRIMARY KEY,
3 firstname VARCHAR(30) NOT NULL,
4 lastname VARCHAR(30) NOT NULL,
5 email VARCHAR(50),
6 reg_date VARCHAR(50)
7 )

This will create a new table employeeinfo in the database. I will use this table to insert data from the CSV file.
Create MySql Connection in PHP
For importing and exporting database in MySql will make a separate file config.php. Add the following code and replace the
database credentials with yours. You can find your db credentials in Application Access details:
1 <?php
2 function getdb(){
3 $servername = "localhost";
4 $username = "huscqxzwaw";
5 $password = "2WWKxxxxHr";
6 $db = "huscqxzwaw";
7
8 try {
9
10 $conn = mysqli_connect($servername, $username, $password, $db);
11 //echo "Connected successfully";
12 }
13 catch(exception $e)
14 {
15 echo "Connection failed: " . $e->getMessage();
16 }
17 return $conn;
18 }
19 ?>
Related: How To Connect MySQL Database With PHP Websites
Import CSV to MySQL in PHP
After the database has been created, I next need an HTML file that could upload CSV file. For this HTML file, I will use
HTML File uploader in a simple bootstrap form.
Create a file and name it index.php . This is a simple form for uploading CSV file. This file will also show the results in a
simple table on the same page. When the user submits the form, all records will be saved in the database.
First, I will add Bootstrap CDN to index.php.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"


1 crossorigin="anonymous">
2 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
3 crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>
Next, in the body tag, add the following HTML code for the Bootstrap form.
<!DOCTYPE html>
<html lang="en">
1
<head>
2
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
3
crossorigin="anonymous">
4
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
5
crossorigin="anonymous">
6
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
7
crossorigin="anonymous"></script>
8
9
</head>
10
11
<body>
12
<div id="wrap">
13
<div class="container">
14
<div class="row">
15
16
<form class="form-horizontal" action="functions.php" method="post" name="upload_excel"
17
enctype="multipart/form-data">
18
<fieldset>
19
20
<!-- Form Name -->
21
<legend>Form Name</legend>
22
23
<!-- File Button -->
24
<div class="form-group">
25
<label class="col-md-4 control-label" for="filebutton">Select File</label>
26
<div class="col-md-4">
27
<input type="file" name="file" id="file" class="input-large">
28
</div>
29
</div>
30
31
<!-- Button -->
32
<div class="form-group">
33
<label class="col-md-4 control-label" for="singlebutton">Import data</label>
34
<div class="col-md-4">
35
<button type="submit" id="submit" name="Import" class="btn btn-primary button-loading" data-
36
loading-text="Loading...">Import</button>
37
</div>
38
</div>
39
40
</fieldset>
41
</form>
42
43
</div>
44
<?php
45
get_all_records();
46
?>
47
</div>
48
</div>
49
</body>

</html>
You might notice that I have set an action to functions.php file. In the next step, I will create this file and add code to it. I
have also include a method get_all_records() near the end of the file. This method fetches all the records from the
database and display the records in the table on the index page.
Next up, I will create functions.php file and add the following code in it.

1 <?php
2
3
4 if(isset($_POST["Import"])){
5
6 $filename=$_FILES["file"]["tmp_name"];
7
8
9 if($_FILES["file"]["size"] > 0)
10 {
11 $file = fopen($filename, "r");
12 while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
13 {
14
15
16 $sql = "INSERT into employeeinfo (emp_id,firstname,lastname,email,reg_date)
17 values ('".$getData[0]."','".$getData[1]."','".$getData[2]."','".$getData[3]."','".$getData[4]."')";
18 $result = mysqli_query($con, $sql);
19 if(!isset($result))
20 {
21 echo "<script type=\"text/javascript\">
22 alert(\"Invalid File:Please Upload CSV File.\");
23 window.location = \"index.php\"
24 </script>";
25 }
26 else {
27 echo "<script type=\"text/javascript\">
28 alert(\"CSV File has been successfully Imported.\");
29 window.location = \"index.php\"
30 </script>";
31 }
32 }
33
34 fclose($file);
35 }
36 }
37
38
39 ?>
When the upload button is clicked, the temporary file name will be stored in memory and using the while loop the data is
saved in $getData variable. Once the process has been completed, the data is sorted column wise and then finally inserted
in the employeeinfotable.
Note that fgetcsv() parses lines from the open file, checking for CSV fields and fopen()opens a file or a URL. This code could
be tested by importing a CSV file with test data.
Display the Saved Records
Once the CSV file has been imported, I will display the data through a simple function, get_all_records(), initialized
in index.php. Copy this function to function.php.

1 function get_all_records(){
2 $con = getdb();
3 $Sql = "SELECT * FROM employeeinfo";
4 $result = mysqli_query($con, $Sql);
5
6
7 if (mysqli_num_rows($result) > 0) {
8 echo "<div class='table-responsive'><table id='myTable' class='table table-striped table-bordered'>
9 <thead><tr><th>EMP ID</th>
10 <th>First Name</th>
11 <th>Last Name</th>
12 <th>Email</th>
13 <th>Registration Date</th>
14 </tr></thead><tbody>";
15
16
17 while($row = mysqli_fetch_assoc($result)) {
18
19 echo "<tr><td>" . $row['emp_id']."</td>
20 <td>" . $row['firstname']."</td>
21 <td>" . $row['lastname']."</td>
22 <td>" . $row['email']."</td>
23 <td>" . $row['reg_date']."</td></tr>";
24 }
25
26 echo "</tbody></table></div>";
27
28 } else {
29 echo "you have no records";
30 }
31 }
In this really simple method, I simply selected all the records and displayed these records on the index page through the
method. Whenever the user uploads a CSV file, the records will get saved in the table and then displayed on the index
page.
Export MySQL to CSV With PHP
Exporting data from MySQL database to a CSV file is similarly very easy. To demonstrate this, I will use the index.php that I
created earlier.
Add the following code to the file.

1 <div>
2 <form class="form-horizontal" action="functions.php" method="post" name="upload_excel"
3 enctype="multipart/form-data">
4 <div class="form-group">
5 <div class="col-md-4 col-md-offset-4">
6 <input type="submit" name="Export" class="btn btn-success" value="export to excel"/>
7 </div>
8 </div>
9 </form>
10 </div>
After adding this HTML markup, the Export button will appear below the table. Now add the following condition
in functions.php.

1 if(isset($_POST["Export"])){
2
3 header('Content-Type: text/csv; charset=utf-8');
4 header('Content-Disposition: attachment; filename=data.csv');
5 $output = fopen("php://output", "w");
6 fputcsv($output, array('ID', 'First Name', 'Last Name', 'Email', 'Joining Date'));
7 $query = "SELECT * from employeeinfo ORDER BY emp_id DESC";
8 $result = mysqli_query($con, $query);
9 while($row = mysqli_fetch_assoc($result))
10 {
11 fputcsv($output, $row);
12 }
13 fclose($output);
14 }
When the Export button is clicked, the headers Content-Type: text/csv with an attachement data.csv is sent.
Since php://output is a write-only stream that allows write access to the output buffer mechanism, I selected all data from
table in the next line, and passed it to fputcsv() method. This method formats a line (passed as a fields array) as CSV and
write it (terminated by a newline) to the specified file. Finally, the file with all the desired data is downloaded.
Finally, after integrating all the code, you will see the following final shape of application.
<?php

//connect to the database


$connect = mysql_connect("localhost","username","password");
mysql_select_db("mydatabase",$connect); //select the table
//

if ($_FILES[csv][size] > 0) {

//get the csv file


$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");

//loop through the csv file and insert into database


do {
if ($data[0]) {
mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//

//redirect
header('Location: import.php?success=1'); die;

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-


transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>

<body>

<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>

<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">


Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>

</body>
</html>

SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `contacts`;
CREATE TABLE `contacts` (
`contact_id` int(11) NOT NULL auto_increment,
`contact_first` varchar(255) character set latin1 default NULL,
`contact_last` varchar(255) character set latin1 default NULL,
`contact_email` varchar(255) character set latin1 default NULL,
PRIMARY KEY (`contact_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

You might also like