【发布时间】:2018-02-02 22:45:11
【问题描述】:
我首先从 TEST 数据库中检索数据
$Sql = "SELECT * FROM test";
$result = array();
$res = mysqli_query($conn, $Sql);
while($row = mysqli_fetch_array($res, MYSQL_NUM)){
$result[] = $row;
}
SESSION 中存储的数据
$_SESSION['Sql'] = $result;
从 SESSION 或 Result 完美打印
echo '<pre>';
print_r($_SESSION['Sql']);
echo '</pre>';
echo '<pre>';
print_r($result);
echo '</pre>';
结果 - 数据库中只有 2 条记录,3 列
Array
(
[0] => Array
(
[0] => 1
[1] => Kent Mercer
[2] => 53
)
[1] => Array
(
[0] => 2
[1] => Linda Carter
[2] => 63
)
)
然后我尝试插入 TEST2 数据库
$fields = implode(",", array_keys($_SESSION['Sql']));
$newdata = implode(",", $_SESSION['Sql']);
$query = ("INSERT INTO test2 ($fields)
VALUES ('$newdata')");
if (mysqli_query($conn, $query)) {
echo "New record created successfully";
}
else{
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
我收到以下错误
Error: INSERT INTO test2 (0,1) VALUES ('Array,Array')
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '0,1)
VALUES ('Array,Array')' at line 1
【问题讨论】:
-
MYSQL_NUM返回数字键,你要MYSQLI_ASSOC -
我改为 MYSQLI_ASSOC & MYSQLI_BOTH。同样的错误。谢谢你的帮助。
-
您对 SQL 注入持开放态度。我会创建一个类来构建您的查询(有关更多信息,请参阅this 答案。然后我会使用动态变量将您的变量映射到适当的列以插入 PDO 或 mysqli。