'How to get logged person's user_id from the database and match the user id session with the second table as the foreign key?

$sql = "INSERT INTO useraccounts (name, email, taman, password) VALUES ('" . $_POST['name'] . "', '" . $_POST['email'] . "', '" . $_POST['taman'] . "','" . $_POST['passsword'] . "')";
if ($db->query($sql)) {
    $id = $db->insert_id;
    $query = "";
    $count = count($_POST['barang']);
    for ($i = 0; $i < $count; $i++) {
        $query = "INSERT INTO requestitem (barang, deskripsi, kategori, image, uID) VALUES ( '$barang', '$deskripsi', '$kategori','$newImageName', 
         '$id')";
    }
    if ($db->multi_query($query)) {
        echo
        "<script>
                 alert('Successfully Added!');
                 document.location.href = 'displayRequest.php';
                 </script>";
    } else {
        echo "Failed";
    }
} else {
    echo "Failed";
}

Here is my current code. I would like to seek for help on how can I fix this code in order to insert data in second table by using current user id session as its foreign key in that second table?



Solution 1:[1]

First thing in this code:

for($i=0; $i<$count;$i++){
                $query = "INSERT INTO requestitem (barang, deskripsi, kategori, image, uID) VALUES ( '$barang', '$deskripsi', '$kategori','$newImageName', 
                '$id')";
                }

You maybe wanted to use .= instead of just =. And use ; at the end of sql query.

+be carefull with inserting user data to sql. Escape it to prevent SQL injections!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pepeD