Re: Excel / my SQL

by Kathy Wheeler <kathyw(at)home.albury.net.au>

 Date:  Sat, 2 Feb 2002 06:43:34 +1100
 To:  "Tamara Nelson" <tamara(at)sanctusmoo.com>
 Cc:  <hwg-techniques(at)hwg.org>
 References:  trudi buckeyecablesystem
  todo: View Thread, Original

> I will repeat my question again:  Using PHP/mySQL, how do I import a CSV
> file from Excel?  I need specific, explicit directions...not vague
> suggestions.

Just did this yesterday for a client, so while it's still fresh and handy:

Have both the csv file exported from excel and this script on your php/MySQL 
server. You can probably do it remotely but it's extra code ... 

Modify for your file names etc ... and assumes you have the MySQL database, 
tables and fields created and permission to insert to them.

SCRIPT STARTS BELOW

<?php

// Connect to your MySQL database and select the database you want to alter:
mysql_pconnect("localhost","username","password");
mysql_select_db("yourMySQLdatabase");

// Open your csv file, error handling, yadda yadda:
if(!$stuff=fopen("yourcsvfile.csv", "r")) {
	echo "Sorry, can't read it.";
	}
else {
	while(!feof($stuff))	{
		$data=fgetcsv($stuff, 4096);
		mysql_query("insert into your_target_table (table, fields, separated, by, 
commas) VALUES 
('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')");
		}
// handy in case you have a syntax error in your sql insert statement:
	echo mysql_errno().": ".mysql_error()."<BR>";
	fclose($stuff);
	}
?>

SCRIPT ENDS ABOVE

// are comment lines; leave them or delete them, it's of no consequence.

file names have been changed to protect the innocent/guilty ;-)

If you need more help you can contact me off list.

Cheers,
KathyW.

HWG hwg-techniques mailing list archives, maintained by Webmasters @ IWA