使用两个数组参数更新数据库

时间:2018-10-29 09:24:14

标签: php sqlite

我正在尝试使用通过表单发送的信息更新数据库。 我的问题是我不知道如何同时循环两个数组。我尝试嵌套foreach循环没有成功。

然后我可以使用它

$display = $_POST["show"] ?? "";
$id = array_keys($_POST["show"]);

if ($action == "submit") {
foreach ($display as $key => $value) {
        $stmt = $db->prepare("UPDATE picture SET display = ? WHERE id = ?");
        $stmt->bindParam($display, $id)
        $stmt->execute();
}
 }

2 个答案:

答案 0 :(得分:1)

您可以遍历数组并同时获取键和值:

$display = $_POST["show"] ?? [];

// Also you can check if `$display` is not empty
if ($action == "submit" && $display) {
    // prepare statement ONCE
    $stmt = $db->prepare("UPDATE picture SET display = ? WHERE id = ?");
    foreach ($display as $key => $value) {
        // execute statement as many times as you want with your params
        $stmt->execute([$value, $key]);
    }
}

答案 1 :(得分:1)

如果我没看错的话,这就是您想要的:

<?php

    try {
        $display = isset($_POST['show']) ? $_POST['show'] : [];
        if ($action === 'submit' && !empty($display)) {
            $db->beginTransaction();
            $stmt = $db->prepare('
                UPDATE picture
                SET display = :display
                WHERE id = :id;
            ');
            foreach ($display as $id => $show) {
                $stmt->bindParam(':display', $show);
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
            }
            $db->commit();
        }
    } catch(PDOException $e) {
       echo $e->getMessage();
       $db->rollBack();
    }