Hi All,
Is there any script by which I can upload CSV file with thousands of records in to mysql database.
Thanks
CSV file uploading with thousands of records
Moderator: General Moderators
-
Mark Baker
- Forum Regular
- Posts: 710
- Joined: Thu Oct 30, 2008 6:24 pm
Re: CSV file uploading with thousands of records
phpmyadmin?
Re: CSV file uploading with thousands of records
Thanks for you reply, but I want PHP code to do that.
-
Mark Baker
- Forum Regular
- Posts: 710
- Joined: Thu Oct 30, 2008 6:24 pm
Re: CSV file uploading with thousands of records
phpmyadmin?pbs wrote:Thanks for you reply, but I want PHP code to do that.
Re: CSV file uploading with thousands of records
offtopic:
you can use load data infile for that
As for the php script, without knowing the table name and column names... does the CSV file include column names as first line? Should be there any mapping?
you can use load data infile for that
As for the php script, without knowing the table name and column names... does the CSV file include column names as first line? Should be there any mapping?
Re: CSV file uploading with thousands of records
This is the script I use to upload a .csv into mysql. I haven't used it in a while, but I believe the column names in the .csv need to match the fields in the table. Replace 'username', 'password', 'your_db', 'your_file.csv' and 'your_table' with your values. I've uploaded about 2500 records into my db at once this way.
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("your_db", $con);
$fcontents = file ('./your_file.csv');
for($i=0; $i<sizeof($fcontents); $i++) {
$line = trim($fcontents[$i], ',');
$arr = explode(',', $line);
$sql = 'INSERT INTO your_table VALUES ("' . implode('","', $arr) . '")';
mysql_query($sql);
echo $sql .'<br>';
if(mysql_error()) {
echo mysql_error() .'<br>';
}
}
mysql_close($con);
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("your_db", $con);
$fcontents = file ('./your_file.csv');
for($i=0; $i<sizeof($fcontents); $i++) {
$line = trim($fcontents[$i], ',');
$arr = explode(',', $line);
$sql = 'INSERT INTO your_table VALUES ("' . implode('","', $arr) . '")';
mysql_query($sql);
echo $sql .'<br>';
if(mysql_error()) {
echo mysql_error() .'<br>';
}
}
mysql_close($con);