A nice and easy way to upload a .csv file into a database, maybe useful for some sort of web app where the user doesn't have access to the likes of phpmyadmin but still needs the ability to upload huge amounts of organised data.

A few minor changes will need to be made depending on how many columns you are wanting to import, simply edit the prepare statement to match the number of columns you have in your table.

You must have the PDO extension installed to use this script, as of PHP 5.1.0, PDO is enabled by default.

Source Code


/*
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

<?php

// Connection Setup
$db_type = "mysql";
$db_host = "localhost";
$db_name = "example-db-name";
$db_user = "example-db-user";
$db_pass = "example-db-password";
 
try {
// Establish Connection
$db = NEW PDO("$db_type:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$db->SetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
// Change the below to match your database setup
$import = $db->prepare('INSERT INTO table_name_here (heading1, heading2, heading3) VALUES (?, ?, ?)');
}
 
// Catch errors
catch(PDOException $e) {
echo "ERROR: " . $e->GetMessage();
}
 
// make sure this matches the name of your submit button
if ($_POST['submit'] == 'send') {
 
	// Check if file is .csv
	$filename = $_FILES['csv']['name'];
	$extension = explode('.', $filename);
	$extension = array_pop($extension);
 
	if (strtolower($extension) == "csv") {
 
		// Set temp name and then open
		$temp_name = $_FILES['csv']['tmp_name'];
		$handle = fopen($temp_name, 'r');
 
		// Loop through the file and get contents via fgetcsv into an array
		while (($items = fgetcsv($handle, 1000, ',')) !== FALSE) {
 
			// Execute prepared query
			$import->execute($items);
 
			// Display whats been added to the database (messy at the moment sorry.)
			echo "<p>";
			foreach ($items as $value) {
				echo stripslashes(htmlspecialchars($value));
			}
			echo "</p>\n";
		}
 
		// Close the opened file
		fclose($handle);
		echo "Success.";
 
	} else {
 
	// Show error message if the file isnt .csv
	echo "Not a CSV file.";
	}	 	 
}
 
?>