PHP - 尝试通过for循环将数据插入数据库但只填充了一行

时间:2016-10-09 14:10:17

标签: php mysql for-loop insert cycle

我正在尝试使用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 个答案:

答案 0 :(得分: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;
            }  

        }