【问题标题】:Taking off the last comma from INSERT into WHILE loop [duplicate]将最后一个逗号从 INSERT 取出到 WHILE 循环中[重复]
【发布时间】: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


【解决方案1】:

使用 rtrim() 函数去除字符串末尾的任何字符

rtrim($string, ",")

【讨论】:

    【解决方案2】:

    可能的解决方案

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

    【讨论】:

      【解决方案3】:

      rtrim 删除字符串的最后一个字符的替代方法是使用substr。以下将提取$string 的一部分(除了最后一个字符之外的所有内容)并重新分配给$string

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-24
        • 2017-03-24
        • 1970-01-01
        • 1970-01-01
        • 2018-02-14
        • 1970-01-01
        相关资源
        最近更新 更多