Mattimat Mattimat - 1 year ago 127
PHP Question

Mysqli can't insert multiple rows

$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();


When i do this only the first row will be added. How do i insert multiple rows?

Answer Source

Just get rid of that multi query thing. Use a prepared statement instead

$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";

Note that your current code with multi_query won't work as intended anyway, even with that silly typo fixed. You will have the result of only first query, having no idea what happened to all others.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download