Re: Validate CSV file With Table in Database!!

From: Date: Thu, 13 Sep 2001 13:31:08 +0000
Subject: Re: Validate CSV file With Table in Database!!
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-67193@lists.php.net to get a copy of this message
Coenraad, Here are some links to relevant sections of the php manual. What you want to do is not too hard at all. I'm assuming that you want to "upload" the csv file via a web page. This is much less trouble for the user than fooling around with ftp. They get to browse their computer for the file and then upload with a single click. 1. Uploading a file http://www.php.net/manual/en/features.file-upload.php#features.file-upload.post-method 2. Opening the uploaded file http://www.php.net/manual/en/function.fopen.php 3. Reading fields from the uploaded file http://www.php.net/manual/en/function.fgetcsv.php 4. Updating the table It depends what database you are using as to how you do this. The obvious approach is to SELECT for each row in your csv file, and then either UPDATE it or INSERT a new one, depending on whether you found it. So putting it altogether you want something like this. You'll have to check the syntax, add error checks etc., and this is based on mysql as the database:- // refreshdata.php <?php if ($mycsvfile != '') { $fp = fopen($mycsvfile); mysql_connect(); while (list($keyfield,$datafield) = fgetcsv($fp)) { $cur_table = mysql_query("select datafield from mytable where keyfield ='".$keyfield."'"); if (mysql_num_rows($cur_table) == 0) { $ins_table = mysql_query("insert into mytable (keyfield,datafield) values ('".$keyfield."','".$datafield."'); } else { $upd_table = mysql_query("update mytable set datafield = '".$datafield."' where keyfield = '".$keyfield."'); } } mysql_close(); fclose($fp); } ?> <HTML> <BODY> <FORM enctype=multipart/form-data method=post> CSV file : <INPUT TYPE=FILE NAME=mycsvfile> <INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML> Coenraad Steenkamp wrote: > > I need to compare a csv file to a table in the database but only one field > in the database with > one field in the CSV file! Comparing only one field will make it much > easier! When there is any change in the Database compared to the CSV file , > the database must then be updated or if there are no such a field it must be > added to the table! > > I am new in php Please help!

« previous php.general (#67193) next »