(MySQLi程序)INSERT INTO(...)WHERE ID = SESSION ID

时间:2019-07-04 18:11:43

标签: php mysql mysqli

我想将数据插入MySQL数据库,应在其中插入数据的列必须取决于会话ID。

<?php

session_start();

if (isset($_POST["mybutton"])) {

    $favcolor = $_POST["mybutton"];

    switch ($favcolor) {
        case "0":
            $sql = "INSERT INTO preferences (color) VALUES ('colord_id_1') WHERE id = $_SESSION['id']";
            mysqli_query($conn, $sql);
            break;
        case "1":
            $sql = "INSERT INTO preferences (color) VALUES ('colord_id_2') WHERE id = $_SESSION['id']";
            mysqli_query($conn, $sql);
            break;
    }
}

mysqli_close($conn);

1 个答案:

答案 0 :(得分:1)

您要更新记录,而不是插入新记录:

$stmt = $conn->prepare("UPDATE preferences SET color='colord_id_1' WHERE id=?");
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();

程序样式:

$stmt = mysqli_prepare($conn, "UPDATE preferences SET color='colord_id_1' WHERE id=?");
mysqli_stmt_bind_param($stmt, 'i', $_SESSION['id']);
mysqli_stmt_execute($stmt);