Create A Database in MySQL
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.
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.
</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
if ($_FILES[csv][size] > 0) {
//redirect
header('Location: import.php?success=1'); die;
?>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
</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;