Import CSV to MySQL using PHP

In my course of work, I normally come across many small problems that I am asked to solve and here is one of the simpler ones. The following code is for developers looking for an easy way to import a comma separated values (CSV) file into a mysql database via PHP. The code below adds contacts from an uploaded CSV file into a MySQL table, populating three fields (name, email, phone) <?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 (name,email,phone) 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" ""> <html xmlns=""> <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>   A sample CSV file would look like this John Doe,,555 4567 Mary Jane,,555 7654 You can, of course, edit for validation and manipulation of the data easily in the loop. Please note that the code will work with CSV created from most common spreadsheet applications including all versions of Excel, and Calc. Happy coding 🙂


Leave a Reply