[eluser]somewhatjaded[/eluser]
In the process of reading in a csv (created w/ CI dbutil), and mapping out values to a database for import, I found the following solution for escaping any data (as it changed slightly when coming back from an excel save). I wasn't able to use mysql_real_escape_string with an array_walk, due to the scoping.
Using
Code:
array_walk($fdata,'mysql_real_escape_string');
produces the following error:
Quote:A PHP Error was encountered
Severity: Warning
Message: mysql_real_escape_string() expects parameter 2 to be resource, integer given
I'm sure there's another way to pass in the correct namespace. 2nd param of array_walk is:
Code:
array("DON'T KNOW", 'mysql_real_escape_string)
but I wasn't able to find it.
Here's my solution, using a virtual function:
Code:
$handle = fopen($udata['full_path'], "r"); //from the upload library
while (($fdata = fgetcsv($handle, 1000, "\t")) !== FALSE)
{ //some examples online use '$data' ...don't do it, it will screw up your views
array_walk($fdata,create_function('&$v, $k','$v = mysql_real_escape_string($v);'));
$this->model->your_function($fdata,$another_param,..,$n); //$fdata has now been escaped
}
fclose($handle);
I realize you could just sanitize within the model, but it seemed to make more sense to pass in clean data, to make the model function more reusable.
Hope that saves someone else the struggle!
*EDIT
I was also able to use the following with success:
Code:
$handle = fopen($udata['full_path'], "r"); //from the upload library
while (($fdata = fgetcsv($handle, 1000, "\t")) !== FALSE)
{ //some examples online use '$data' ...don't do it, it will screw up your views
$zdata = array_map('mysql_real_escape_string',$fdata); //USING array_map instead, create temp array.
$this->model->your_function($zdata,$another_param,..,$n); //$fdata has now been escaped
}
fclose($handle);
Keep in mind this creates a temporary array, so if this doesn't bother you, go for it.
Using the profiler, they both seem to use approx. the same memory/execution time for a small file, with the array_map possible having a slight edge in performance, and array_walk the edge in job security :coolsmirk: