Re: Text from Excel csv file loaded into MySQL table

From: Date: Tue, 17 Oct 2006 17:12:18 +0000
Subject: Re: Text from Excel csv file loaded into MySQL table
References: 1 2 3 4  Groups: php.general 
Request: Send a blank email to php-general+get-243253@lists.php.net to get a copy of this message
On Tue, October 17, 2006 2:36 am, Alan Milnes wrote: >> <?php >> $file = fopen($filename, "r") or die("Could not open $filename"); >> while (!feof($file)){ >> $values = fgetcsv($file, 1000000); >> array_walk($values, 'mysql_real_escape_string'); >> $values_sql = implode("', '", $values); >> $query = "insert into invw2wfinal "; >> $query .= "values('$values') "; >> $result = mysql_query($query) or die(mysql_error()); >> } >> ?> >> >> This assumes that no record (all 4 fields) with overhead is move >> than >> 1Mb in size -- Change the 1000000 if you have monster fields. And >> count on needing to tweak my.cnf in that case anyway. >> > Looks a lot neater than my code! Is it version dependent? Running on > MySQL 4.1.21 and PHP 4.4.4 (not my Server so I can't control that) > generates the following warnings:- > > "mysql_real_escape_string() expects parameter 2 to be resource, > integer" Dang. Yeah, array_walk passes in the key as second arg, and we wanted nothing. You'll have to write your own custom function like: function my_mysql_real_escape_string($value, $key, $connection){ return mysql_real_escape_string($value, $connection); } and then change it to: array_walk($values, 'my_mysql_real_escape_string', $connection); where $connection is the return value from your mysql_connect call. Or just skip all the $connection parts everywhere above to use the last-opened connection. > for each of the fields then when it goes to do the query it returns > "Column count doesn't match value count at row 1", if I echo the query > it reads "insert into invw2wtest values('Array')". D'oh! Change $values to $values_sql in the $query line. I'm not sure in what version mysql_real_escape_string first appeared, but it's in the manual. http://php.net/mysql_real_escape_string -- Some people have a "gift" link here. Know what I want? I want you to buy a CD from some starving artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So?

« previous php.general (#243253) next »