-3

I want to insert data into MySQL database, the column where the data should be inserted must depend on the session 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);
Qirel
  • 25,449
  • 7
  • 45
  • 62
  • 2
    There is no `INSERT INTO ... WHERE`. Either you insert the id, or you update the row. So the question is, is there already a row with that ID? Or do you wish to insert a new row with that ID? – Qirel Jul 04 '19 at 18:13
  • The ID already exists, (id, email, password, color, etc), ID is incremental, thus I want to insert that data in the ID of the particular user. – Iskren Lalov Jul 04 '19 at 18:16
  • You could even avoid the long switch statement altogether by using array. – Dharman Jul 04 '19 at 18:19
  • Just to make sure, show us the schema for your `preferences` table – RiggsFolly Jul 04 '19 at 18:20
  • @RiggsFolly I think OP knows his code produces error, but he was trying to solve the problem himself anyway. – Dharman Jul 04 '19 at 18:21
  • It is the wrong approach IMHO. The setting "color" is most likely tied to a User (and his ID in the database). A session, as well as a session id, is volatile and session_id regeneration is a very common method to counter session fixation attacks. Or when the session expires and isn't picked up again, it will eventually being garbage collected and the session id is gone forever. Only the record in your database remains as garbage... – Honk der Hase Jul 04 '19 at 19:29

1 Answers1

1

You want to update the record instead of inserting new one:

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

Procedural style:

$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);
Dharman
  • 30,962
  • 25
  • 85
  • 135