【问题标题】:PHP - trying to insert data into database through for-loop but only one row is filledPHP - 尝试通过for循环将数据插入数据库但只填充了一行
【发布时间】:2016-10-09 14:10:17
【问题描述】:

我正在尝试使用 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 并在外部调用查询,这意味着只会插入一条记录。

标签: php mysql for-loop insert cycle


【解决方案1】:

您的问题是运行插入的 $conn-&gt;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;
            }  

        }  

【讨论】:

    猜你喜欢
    • 2017-07-28
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 2020-05-25
    • 2020-05-13
    相关资源
    最近更新 更多