0

here is the code:

    if (($handle = fopen($source_file, "r")) !== FALSE) {
    $columns = fgetcsv($handle, $max_line_length, ",");
    foreach ($columns as &$column) {
        $column = str_replace(".","",$column);
    }
    while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
        while(count($data) < count($columns)) {
            array_push($data, NULL);
        }
        $c = count($data);
        for($i = 0; $i < $c; $i++) {
            $data[$i] = "'{$data[$i]}'";
        }

        $sql[] = '(' . implode(',',$data) . ','.$_POST[group].')';
    }
            $sql = implode(',',$sql);

    $query = "INSERT INTO mytable (".mysql_real_escape_string(implode(",",$columns)).",Custgroup,user_id) VALUES " 
                      . $sql . "\n";
    mysql_query($query) or trigger_error(mysql_error());

    fclose($handle);
      }
     } 

If my csv file is:

lastname,firstname,gender

bob,ah,male

So now the query will be : INSERT INTO mytable (lastname,firstname,gender) VALUES ('bob','ah','male'). But how if I want to insert extra data into mysql together with the data in csv file? Such as I have a value $_POST['group'] = 'family' and $_POST['user_id'] = '10', so I tried:

$sql[] = '(' . implode(',',$data) . ','.$_POST[group].','.$_POST[user_id].')';

$query = "INSERT INTO $target_table (".mysql_real_escape_string(implode(",",$columns)).",custgroup,user_id) VALUES " 
                      . implode(',',$sql) . "\n";

But in the query it will become : INSERT INTO mytable (lastname,firstname,gender,custgroup,user_id) VALUES ('bob','ah','male',family,10). It didn't have single quote , so I have error to insert the record.Can I know how to solve this problem?

1
  • what's the point in doing mysql_real_escape_string(implode(',', $columns))? Commented Nov 9, 2011 at 8:20

2 Answers 2

1

try this:

$sql[] = '(' . implode(',', $data) . ", '" . $_POST['group'] . "'," . $_POST['user_id'] . ')';

$query = "INSERT INTO $target_table (" . mysql_real_escape_string(implode(',', $columns)) . ',custgroup,user_id) VALUES ' . implode(',', $sql);
Sign up to request clarification or add additional context in comments.

2 Comments

Thankyou so much.Now the query is: INSERT INTO UserAddedRecord (lastname,firstname,cell,custgroup,user_id) VALUES ('Last','First','042819679', 'Family',1)
what's the point in doing mysql_real_escape_string(implode(',', $columns))?
0

for the sake of readability you might consider the following :

$sql = sprintf("(%s,'%s',%d)",
    implode(',', $data),
    $_POST['group'],
    $_POST['user_id']
);

which gives you more flexibility and understanding in what your code actually performs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.