1

I really need to escape the last comma to prevent SQL errors with the INSERT

Should I use a simple implode, maybe a trim? But how? I don't want to echo those values, just insert them into my database escaping the last comma

    if ($handle = fopen($arquivo['tmp_name'], "r")) {

        $pdo = $this->connector->getConnection();

        $firstLine   = true;

        $string = "INSERT INTO vestibular (rg, nome, curso, resultado, colocacaogeral, colocacaocurso, unidade) VALUES ";

        while ($row = fgetcsv($handle , 0 , ";")) {

            if ($firstLine) {
                $firstLine = false;
                continue;
            }

            $string .= "(
                '" . mb_convert_encoding($row[0], 'UTF-8', 'ISO-8859-1') . "',
                '" . mb_convert_encoding($row[1], 'UTF-8', 'ISO-8859-1') . "',
                '" . mb_convert_encoding($row[2], 'UTF-8', 'ISO-8859-1') . "',
                '" . mb_convert_encoding($row[3], 'UTF-8', 'ISO-8859-1') . "',
                '" . mb_convert_encoding($row[4], 'UTF-8', 'ISO-8859-1') . "',
                '" . mb_convert_encoding($row[5], 'UTF-8', 'ISO-8859-1') . "',
                '" . $_POST['unidadeVestibular'] . "'
                ),";

        }

        $statement = $pdo->prepare($string);
        $statement->execute();

        return $statement;

        fclose($handle);

    }


}

Could someone help me please? =D

EDIT 1 :

TO CLARIFY: I need to prevent a comma into $_POST['unidadeVestibular'] to keep the loop going and Insert as it should do

  • 1
    Honestly, the "easiest" way to do this would be to add each of your rows to an array and then implode the array. (for a given value of easy.) – P. Gearman May 09 '16 at 13:58
  • You could also look at something like `$string = substr($string,0,strlen($string) - 1);` – Jacques Koekemoer May 09 '16 at 13:59
  • Use Prepared, Parameterized Queries. Your code is vulnerable to SQL-Injection and absolutely wrong. If you insert the values directly into the query, then you're rendering the whole preparing process worthless. – Charlotte Dunois May 09 '16 at 14:16

3 Answers3

2

Use rtrim() function to Strip any characters from the end of a string

rtrim($string, ",")
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
1

Possible Solution

$statement = $pdo->prepare(rtrim($string, ","));

$statement->execute();
Megan Fox
  • 435
  • 2
  • 6
  • 20
0

An alternative to rtrim to remove the last character of a string is to use substr. The following will extract part of $string (everything except the last character) and reassign to $string.

$string = substr($string, 0, -1);

Amous
  • 534
  • 5
  • 18