我正在用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;
}
}
答案 0 :(得分:0)
解决方案结果很简单:虽然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] . "'";
}
答案 1 :(得分:-2)
好的,这是我的输入验证功能
function validation_input($data) {
$data = trim($data); /* for filter */
$data = stripslashes($data); /* for filter */
$data = addslashes($data); //$data = str_replace("'", "\'", $data);
$data = htmlentities($data); /* for XSS */
//$data = htmlspecialchars($data);
//$data = htmlspecialchars_decode($data);
return $data;
}
使用PDO准备
$title = validation_input($_POST['nameTitle']);
$stmt = $db->prepare("INSERT INTO blog (title_blog) VALUES (:title)");
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->execute();