0
我試圖插入數據到數據庫使用for循環。這裏是我的代碼:PHP - 試圖通過for循環插入數據到數據庫,但只有一行被填充
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "objednavky";
// ******************************************************
include 'simple_html_dom.php';
$html = file_get_html('http://www.quickbistro.cz/cs/rozvoz');
$count = substr_count($html, '<li class="item">');
$jidloA = array();
$cenaA = array();
// ********************************************************
$conn = mysqli_connect($servername, $username, $password, $dbname);
if ($conn->connect_error) {
$message = "Connection failed: " . $conn->connect_error;
} else {
for ($x = 0; $x <= $count; $x++) {
$cenaA[$x] = $html->find("span[class=price]", $x);
$jidloA[$x] = $html->find("div[class=article]", $x);
$jidloSQL = strip_tags($jidloA[$x]);
$cenaSQL = strip_tags($cenaA[$x]);
$id = $x + 1;
$array = array(
"id" => $id,
"popis" => "$jidloSQL",
"cena" => "$cenaSQL"
);
$sql = "INSERT INTO jidla";
$sql.= " (`" . implode("`, `", array_keys($array)) . "`)";
$sql.= " VALUES ('" . implode("', '", $array) . "') ";
}
}
if ($conn->query($sql) === TRUE) {
echo "Data inserted succesfully";
}
else {
echo "error creating table" . $conn->error;
}
$conn->close();
?>
當我運行它填補了腳本表我只有一排只有ID充滿號81(我想提取項目數)。當我試圖只插入一行而沒有循環時,它是正確的,並且行正確插入了項目,所以我猜測問題在我的for循環中。
不知道你有什麼期待?您在foreach中生成$ sql,並在外部調用查詢,這意味着只會插入一條記錄。 –