Html Code to Upload Csv File to Email

PHP is widely used for edifice a broad range of products ranging from web apps to enterprise level applications. The key to efficient PHP code is to follow proper workflows and automate processes. The issue is high quality and bug-free lawmaking.

In nearly all PHP applications, information is stored, accessed and exchanged betwixt various components of the app. To make sure that this substitution and access to data goes smoothly and without whatever issues, the development team must make sure that the databases and data dumps are in proper format.

how to import and export csv files using php and mysql

Import and export of data to and from databases is a common enough procedure in PHP development. Another important activity is the backup and transfer of databases.

In this article, I volition explain how to save tables from CSV files to MySQL and vice versa. You need to signup at Cloudways to launch a server and PHPstack application. Before signing up, looking at all the pricing options from the world-class hosting providers like AWS, DigitalOcean, Linode, Vultr and GCP is a skillful idea so you can detect the one that perfectly fits your needs.

PHP Hosting: All-time PHP 7 & PHP 5.six Web Hosting

Create a Database in MySQL

The start stride 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 tin create tables by running SQL queries.  Create a table ` employeeinfo` in database using the following SQL query.

CREATE TABLE employeeinfo( emp_id VARCHAR(50) UNSIGNED PRIMARY Central, firstname VARCHAR(30) Not Aught, lastname VARCHAR(30) Non NULL, email VARCHAR(l), reg_date VARCHAR(l) )        

This will create a new table ` employeeinfo` in the database. I will use this table to insert data from the CSV file.

Stop Wasting Time on Servers

Cloudways handle server management for you so yous can focus on creating smashing apps and keeping your clients happy.

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. Y'all can detect your db credentials in Application Access details:

<?php function getdb(){ $servername = "localhost"; $username = "huscqxzwaw"; $countersign = "2WWKxxxxHr"; $db = "huscqxzwaw";  try {         $conn = mysqli_connect($servername, $username, $password, $db);      //echo "Continued successfully";      } catch(exception $e)     {     echo "Connection failed: " . $e->getMessage();     }     return $conn; } ?>        

Related: How To Connect MySQL Database With PHP Websites

Import CSV to MySQL in PHP

Later the database has been created, I next need an HTML file  that could upload CSV file. For this HTML file, I will employ HTML File uploader in a elementary bootstrap form.

Create a file and name information technology ` index.php` . This is a simple form for uploading CSV file. This file will too show the results in a elementary table on the same page. When the user submits the course,  all records will be saved in the database.

Commencement, I will add together Bootstrap CDN to index.php .

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.vii/css/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/three.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>        

Side by side, in the ` body` tag,  add the post-obit HTML code for the Bootstrap form.

<!DOCTYPE html> <html lang="en">  <caput>     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.seven/css/bootstrap.min.css" crossorigin="anonymous">     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/three.3.vii/css/bootstrap-theme.min.css" crossorigin="anonymous">     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.iii.seven/js/bootstrap.min.js" crossorigin="anonymous"></script>  </head>  <body>     <div id="wrap">         <div form="container">             <div class="row">                  <grade course="course-horizontal" action="functions.php" method="post" name="upload_excel" enctype="multipart/form-data">                     <fieldset>                          <!-- Form Name -->                         <legend>Form Proper noun</legend>                          <!-- File Push -->                         <div course="form-group">                             <characterization form="col-md-iv control-label" for="filebutton">Select File</label>                             <div grade="col-md-iv">                                 <input blazon="file" name="file" id="file" class="input-big">                             </div>                         </div>                          <!-- Button -->                         <div class="form-group">                             <label class="col-physician-4 command-label" for="singlebutton">Import data</label>                             <div class="col-md-4">                                 <push button blazon="submit" id="submit" proper noun="Import" grade="btn btn-principal button-loading" information-loading-text="Loading...">Import</button>                             </div>                         </div>                      </fieldset>                 </form>              </div>             <?php                get_all_records();             ?>         </div>     </div> </body>  </html>

import form

You might notice that I have gear up an activeness to ` functions.php` file. In the side by side step, I will create this file and add code to it. I take 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 together the following code in it.

<?php    if(isset($_POST["Import"])){ 		 		$filename=$_FILES["file"]["tmp_name"];		   		 if($_FILES["file"]["size"] > 0) 		 { 		  	$file = fopen($filename, "r"); 	        while (($getData = fgetcsv($file, 10000, ",")) !== FALSE) 	         {   	           $sql = "INSERT into employeeinfo (emp_id,firstname,lastname,email,reg_date)                     values ('".$getData[0]."','".$getData[1]."','".$getData[2]."','".$getData[three]."','".$getData[4]."')";                    $result = mysqli_query($con, $sql); 				if(!isset($result)) 				{ 					repeat "<script type=\"text/javascript\"> 							alarm(\"Invalid File:Please Upload CSV File.\"); 							window.location = \"index.php\" 						  </script>";		 				} 				else { 					  repeat "<script type=\"text/javascript\"> 						alert(\"CSV File has been successfully Imported.\"); 						window.location = \"index.php\" 					</script>"; 				} 	         } 			 	         fclose($file);	 		 } 	}	     ?>        

When the upload button is clicked, the temporary file name will exist 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 cavalcade wise and then finally inserted in the ` employeeinfo` tabular array.

Notation 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 past 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 office to ` function.php` .

office get_all_records(){     $con = getdb();     $Sql = "SELECT * FROM employeeinfo";     $result = mysqli_query($con, $Sql);         if (mysqli_num_rows($result) > 0) {      echo "<div class='table-responsive'><table id='myTable' grade='table table-striped table-bordered'>              <thead><tr><th>EMP ID</th>                           <thursday>First Name</th>                           <thursday>Last Name</th>                           <th>Email</th>                           <th>Registration Date</th>                         </tr></thead><tbody>";        while($row = mysqli_fetch_assoc($result)) {           repeat "<tr><td>" . $row['emp_id']."</td>                    <td>" . $row['firstname']."</td>                    <td>" . $row['lastname']."</td>                    <td>" . $row['email']."</td>                    <td>" . $row['reg_date']."</td></tr>";              }           repeat "</tbody></table></div>";       } else {      echo "you lot take no records"; } }

In this really elementary method, I simply selected all the records and displayed these records on the alphabetize page through the method. Whenever the user uploads a CSV file, the records will go saved in the table and so displayed on the index page.

Export MySQL to CSV With PHP

Exporting information from  MySQL database to a CSV file is similarly very easy. To demonstrate this, I will apply the alphabetize.php that I created earlier.

Add the following code to the file.

          <div>             <form class="course-horizontal" action="functions.php" method="post" proper name="upload_excel"                          enctype="multipart/form-data">                   <div course="form-group">                             <div class="col-doctor-four col-md-showtime-four">                                 <input type="submit" name="Export" form="btn btn-success" value="export to excel"/>                             </div>                    </div>                                 </grade>             </div>        

After calculation this HTML markup, the Exportbutton will appear below the table. Now add the following condition in functions.php.

          if(isset($_POST["Consign"])){ 		        header('Content-Blazon: text/csv; charset=utf-viii');         header('Content-Disposition: attachment; filename=data.csv');         $output = fopen("php://output", "west");         fputcsv($output, array('ID', 'First Proper noun', 'Last Name', 'Email', 'Joining Engagement'));         $query = "SELECT * from employeeinfo ORDER BY emp_id DESC";         $issue = mysqli_query($con, $query);         while($row = mysqli_fetch_assoc($result))         {              fputcsv($output, $row);         }         fclose($output);    }        

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 tabular array in the side by side 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 lawmaking, you volition encounter the following last shape of application.

cloudways import excel

You lot might too like: Elementary CRUD in PHP and MySQL

Determination

In this article, I discussed how you could export data from and to CSV files using PHP and MySQL. This is a elementary instance y'all can Add more complex logic and validations as per your requirements. You can too create exam cases to verify the code and Integerate with GitHub using PHP Continuous Integeration Tools. If yous wish to add together to the give-and-take or would similar to inquire a question, leave a comment beneath.

How exercise I import and export CSV using php and MySQL?

  • Corroborate the submitted record, whether a substantial CSV file.
  • Inspect the CSV file transfer status utilizing PHP is_uploaded_file() function.
  • Admission the CSV file utilizing PHP fopen() part.
  • Parse information from the CSV tape utilizing PHP fgetcsv() role.
  • Insert or updade data into the database based on the fellow member'south electronic mail.

Share your opinion in the annotate section. COMMENT At present

Share This Article

Customer Review at

"Cloudways hosting has one of the best customer service and hosting speed"

Sanjit C [Website Developer]

sayersuntinxion42.blogspot.com

Source: https://www.cloudways.com/blog/import-export-csv-using-php-and-mysql/

0 Response to "Html Code to Upload Csv File to Email"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel