【发布时间】:2016-05-09 13:57:22
【问题描述】:
我真的需要转义最后一个逗号,以防止 INSERT 出现 SQL 错误
我应该使用简单的内爆,也许是修剪?但是怎么做?我不想回显这些值,只需将它们插入到我的数据库中,转义最后一个逗号
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);
}
}
有人可以帮帮我吗? =D
编辑 1:
澄清:我需要防止在$_POST['unidadeVestibular'] 中出现逗号,以保持循环继续进行并按应有的方式插入
【问题讨论】:
-
老实说,“最简单”的方法是将每一行添加到数组中,然后使数组内爆。 (对于给定的easy值。)
-
你也可以看看
$string = substr($string,0,strlen($string) - 1); -
使用准备好的参数化查询。您的代码容易受到 SQL 注入的攻击,而且绝对是错误的。如果将值直接插入到查询中,那么整个准备过程就会变得毫无价值。
标签: php