$allgames = file_get_contents("https://steamspy.com/api.php?request=all");
$decodeall = json_decode($allgames, true);
foreach($decodeall as $game) {
$sql = "INSERT INTO games (name)
VALUES ('{$game['name']}')";
}
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
当我这样做时,只会添加第一行。我如何插入多行?
答案 0 :(得分:1)
摆脱那个多查询的事情。请改用预备语句
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach($decodeall as $game) {
$name = $game['name'];
$stmt->execute();
}
echo "New records created successfully";
请注意,使用multi_query的当前代码无论如何都不会按预期工作,即使修复了这个愚蠢的拼写错误。你将只得到第一个查询的结果,不知道所有其他人发生了什么。
答案 1 :(得分:0)
您每次都要覆盖查询。尝试将sql设置为空白,然后每次在循环中附加它。
试试这个:
$sql = array();
foreach($decodeall as $game) {
$sql[] = "INSERT INTO games (name) VALUES ('{$game['name']}')";
}
$sqlInserts = implode(';', $sql);
if ($conn->multi_query($sqlInserts) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
答案 2 :(得分:0)
您不需要多次执行查询,您可以在没有multi_query()
的单个查询中完成所有操作。您可以使用单个查询执行许多INSERT,例如
// Initialize the query-variable
$sql = "INSERT INTO games (name) VALUES";
// Loop through results and add to the query
foreach ($decodeall as $game) {
$sql .= " ('".$game['name']."'),";
}
// Remove the last comma with rtrim
$sql = rtrim($sql, ',');
// Perform the query
if ($conn->query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
这将生成类似于
的查询INSERT INTO games (name) VALUES ('One'), ('two'), ('Three')
会将值One
,Two
和Three
插入不同的行中。
如果您的$game['name']
变量包含萎缩'
,此查询将中断,因此至少您应该使用$mysqli::real_escape_string()
,尽管准备好的声明需要照顾和会阻止SQL注入(所以我建议你去做)。见How can I prevent SQL injection in PHP?
使用预备声明 - 更好的解决方案
执行查询的首选方法是使用预准备语句。
使用array_column()
获取所有列,并在调用execute方法时循环该数组,直到完成。
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach (array_column($decode, "name") as $name) {
$stmt->execute();
}