【问题标题】:PHP's addslashes() not working for MySQL insertPHP addlashes() 不适用于 MySQL 插入
【发布时间】:2015-06-16 19:13:26
【问题描述】:

我正在用 PHP 编写一个导入脚本以将表从 SQL Server 导入 MySQL,并且我将所有 char/varchar 值包装在单引号中以进行插入。这工作正常,直到脚本遇到一个包含单引号的值。显而易见的解决方案是使用addslashes(),但这对我不起作用。我也试过htmlspecialchars()mysqli_real_escape_string,但都没有成功。我什至尝试使用str_replace("'", "", $value) 完全删除违规字符,但没有成功。最后,我尝试将值用双引号而不是单引号括起来,但是在遇到无法转义值的双引号的行时,这给了我同样的错误。

在出现错误之前,脚本成功地插入了多个块,每块 1,000 行,所以我知道 INSERT 语句的格式不正确。我记录了整个查询并确认单引号没有被转义,尽管我可以手动运行 INSERT,只使用有问题的行并在必要时包含反斜杠。

我被难住了。有没有我遗漏的故障排除提示?

我已经检查了重复或类似的问题,但我没有找到任何适用于我的情况但我尚未尝试过的问题。如果我忽略了之前对此的回答,请告诉我。

代码如下:

// Chunk size
$Insert_Max = 1000;
// Array to hold all rows for the insert
$Insert_Rows = [];  

while($row = mssql_fetch_row($result)) {
    $Insert_Vals = [];

    // Instead of building up a tedious string for each insert, let's do it programmatically
    $offset = 0;

    while ($offset < mssql_num_fields($result)) {
        $field_type = mssql_field_type($result, $offset);   

        if (empty($row[$offset])) {
            $Insert_Vals[] = "NULL";
        } else {
            if ($field_type == "int" || $field_type == "bit") {
                $Insert_Vals[] = $row[$offset];
            } else if (strpos($field_type, "char") !== false) { // Covers char, varchar, nvarchar
                $Insert_Vals[] = "'" . addslashes($row[$offset]) . "'";
            } else {
                $Insert_Vals[] = "'" . $row[$offset] . "'";
            }               
        }

        $offset++;
    }

    $Insert_String = "(" . implode(",", $Insert_Vals) . ")";

    $Insert_Rows[] = $Insert_String;

    $count++;
    if ($count >= $Insert_Max) {
        // $Insert_Header =  "INSERT INTO tablename (col1, etc.) VALUES "
        $internal_connection_object->Perform_The_Insert($Insert_Header, $Insert_Rows);
        $count = 0;
    }
}

【问题讨论】:

  • 它是否在任何地方打印某种错误?
  • 你有没有同时使用htmlspecialchars()mysqli_real_escape_string()?您需要发布一些代码。传入值和函数放置/使用可能是一个问题和函数组合。也可以尝试准备好的语句。
  • 希望您使用的是 mysqli 库。这就是准备好的陈述所针对的情况。
  • @bemontibeller - 错误打印到控制台,显示“您的 SQL 语法有错误;请检查与您的 MariaDB 服务器相对应的手册...”,字符串 sn-p 开头为单引号。
  • 我会让你们解决这个问题。这里厨房里的厨师太多了。可能会破坏汤。

标签: php mysql addslashes


【解决方案1】:

解决方案很简单:虽然 SQL Server 上的值为 VARCHAR(255),但它以 TEXT 形式传入 MySQL。我通过将(data type: $field_type) 附加到插入中的每个值来看到这一点。在 VARCHAR 条件中考虑 TEXT 解决了这个问题。

if ($field_type == "int" || $field_type == "bit") {
    $Insert_Vals[] = $row[$offset];
} else if (strpos($field_type, "char") !== false || $field_type == "text") { 
    // Covers char, varchar, nvarchar, and now text
    $Insert_Vals[] = "'" . addslashes($row[$offset]) . "'";
} else {
    $Insert_Vals[] = "'" . $row[$offset] . "'";
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 2011-03-02
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    相关资源
    最近更新 更多