开发者

How can I do this with a loop so I dont have to do it manually for array data[]

How can I do this as a loop, so I don't have to do it manually for each element of the array?

 $filename=$_POST['filename'];
 $handle = fopen("$filename", "r");
 while (($data = fgetcsv($handle, 5000, ",")) !== FALSE)
 {  
    $data[0] = mysql_escape_string($data[0]);   /// customer id
    $data[1] = mysql_escape_string($data[1]);   /// first name
    $data[2] = mysql_escape_string($data[2]);   /// last name
    $data[3] = mysql_escape_string($data[3]);   /// email
    $data[4] = mysql_escape_string($data[4]);   /// phone
    $data[5] = mysql_escape_string($data[5]);   /// mobile
    $data[6] = mysql_escape_string($data[6]);   /// website
    $data[7] = mysql_escape_string($data[7]);   /// DOB
    $data[8] = mysql_escape_string($data[8]);   /// spouse first name
    $data[9] = mysql_escape_string($data[9]);   /// spouse last name
    $data[10] = mysql_escape_string($data[10]); /// spouse cell
    $data[11] = mysql_escape_string($data[11]);  /// spouse email
    $data[12] = mysql_escape_string($data[12]);  //// created by
    $data[13] = mysql_escape_string($data[13]);  //// created on
}开发者_JAVA技巧


something like:-

put this in your while loop

$count=count($data);
    for ($i=0; $i< $count; $i++)
    {
      $data[$i] = mysql_escape_string($data[$i]); 
    }


array_map, array_walk, or foreach. put one (and only one!) these inside while loop

 $dataSafe = array_map('mysql_escape_string', $data);

or

array_walk($data, function(&$x) {$x = mysql_escape_string($x);});

Note that array_map is like map in the FP sense, it returns a new array and you must assign. array_walk can alter your array in place when & is used

http://php.net/manual/en/function.array-walk.php
http://php.net/manual/en/function.array-map.php

foreach(&$data as $x)
    $x = mysql_escape_string($x)

PS - mysql_real_escape_string is preferred


Alternatively you can put this in your while loop:

$data = array_map("mysql_escape_string", $data);

I haven't tested it but it may be faster.

edit: Added "$data = " - as jon_darkstar pointed out array_map does not change the array provided as a parameter, you need to assign it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜