Skip to content

Instantly share code, notes, and snippets.

@bcalloway
Created March 7, 2009 20:07
Show Gist options
  • Save bcalloway/75424 to your computer and use it in GitHub Desktop.
Save bcalloway/75424 to your computer and use it in GitHub Desktop.
Import a csv file into MySQL
<?php
//Define Variables
$host='localhost'; //hostname of database
$user='user'; //username of database
$pass='pass'; //password of database
$dbname='database'; //name of database
$table='table'; //name of table
$file='spreadsheet.csv'; //name of file to be imported (including extension)
///////////Do not edit below this line!/////////////////////
//Connect to MySQL Database
if ($dbc = @mysql_connect ($host, $user, $pass)) {
if (!@mysql_select_db ($dbname)) {
die ('<p>Could not select the database because: <b>' . mysql_error() . '</b></p>');
}
} else {
die ('<p>Could not connect to MySQL because: <b>' . mysql_error() . '</b></p>');
}
$fcontents = file ('./stafflist.csv');
# expects the csv file to be in the same dir as this script
for($i=0; $i<sizeof($fcontents); $i++) {
$line = trim($fcontents[$i]);
$arr = explode(",", $line);
#if your data is comma separated
# instead of tab separated,
# change the '\t' above to ','
$sql = "insert into $table values ('".
implode("','", $arr) ."')";
mysql_query($sql);
echo $sql ."<br>\n";
if(mysql_error()) {
echo mysql_error() ."<br>\n";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment