Re: Text from Excel csv file loaded into MySQL table

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux