2016-10-09 67 views
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循環中。

+1

不知道你有什麼期待?您在foreach中生成$ sql,並在外部調用查詢,這意味着只會插入一條記錄。 –

回答

2

你的問題是,你的$conn->query($sql)它運行插件是不是你for循環內,因此它沒有被在每個循環中運行,它的唯一正在運行for循環結束後,因此它只能插入最終循環的結果。

嘗試做這種方式:

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 record" . $conn->error; 
      } 

     } 
相關問題