Question

Hi I need a hand with a code that I'm doing, I would like to place the field number in the code but failed to remove it:

My current code:

ini_set('memory_limit',  -1);
error_reporting(0);
$lines = array();
if (($handle = fopen("test.csv", "r")) !== false)
{

    while (($data = fgetcsv($handle, 0, ',')) !== false)
    {
        if (isset($fields))
        {
            $lines[] = $data;
        }
        else
        {
            $fields = $data;
        }
    }

    fclose($handle);
}

$i="0";
$line[$k] = '".addslashes($data['.$i.'])."';
$i++;

$sql .= '$update = "UPDATE `Test` SET <br />`' . implode($fields, '` = \'' . implode($line, '\', \'') . '\',<br />`') . '` = \'".addslashes($data[0])."\'' . "\n";

echo $sql;

My csv its:

test1,test2,test3,test4,test5,test6

i need output:

$update = "UPDATE `Test` SET 
`test1` = '".addslashes($data[0])."',
`test2` = '".addslashes($data[1])."',
`test3` = '".addslashes($data[2])."',
`test4` = '".addslashes($data[3])."',
`test5` = '".addslashes($data[4])."',
`test6` = '".addslashes($data[5])."'

My code only output:

$update = "UPDATE `Test` SET 
`test1` = '".addslashes($data[0])."',
`test2` = '".addslashes($data[0])."',
`test3` = '".addslashes($data[0])."',
`test4` = '".addslashes($data[0])."',
`test5` = '".addslashes($data[0])."',
`test6` = '".addslashes($data[0])."'

Any Idea??

Was it helpful?

Solution

Why not put it inside a loop and directly construct it, consider this as an example:

$data = array();
if (($handle = fopen("test.csv", "r")) !== false) {
    while(!feof($handle)) {
        $fields = fgetcsv($handle, 1024);
    }

    foreach($fields as $key => &$value) {
        $value = $value = '`' . $value . '`' . ' = ' . '".addslashes($data['.$key.'])."';
    }

    fclose($handle);
}

$sql .= '$update = "UPDATE `Test` SET <br />`' . implode("<br/>\n", $fields);
echo $sql;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top