Database doesnt get updates when i try to use SESSION to insert user ID as foreign key in task table

I have two tables which are user and tasks. I want the users ID to get inserted as a foreign key into the tasks table when i add a new task. But when I run this i dont get an error message from the browser nor is my database updating. Ive tried allowing the user to insert their own id manually and that got recorded in the database but when i try using session to get it automatically i get nothing. Im new to this so im a little clueless. If someone could please take a look and tell me what im missing?

    <form method="post" action="" name="tasksinputs">
      <li><label for ="name"> <b>Task name</b> </label></li>
        <input type="text" name="name" class="input">

      <li><label for ="datep"> <b>Date of notification</b> </label></li>
        <input type="date" name="datep" class="dates">

      <li><label for ="datef"> <b>Deadline</b> </label></li>
        <input type="date" name="datef" class="dates">


	    <button type="submit" name="submit" class="add_button">Add Task</button>





if (isset($_POST['submit'])) {

        $name = $_POST['name'];
        $datep = $_POST['datep'];
        $datef = $_POST['datef'];
        $id = $_SESSION['login_employee'];
            $query = "INSERT INTO tasks SET task=?, datepost=?, deadline=?, eid =?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param('sssi', $name, $datep, $datef, $id);
            $result = $stmt->execute();
            if ($result) {
                echo 'it finally worked';
            } else {
              echo 'mannn you dead';

I get ‘mannn you dead’ after i click the add task button.

The session variable is an input to your code. You must validate all inputs before using them. For external data, you must also trim them before validating them, so that you can detect if they consisted of all white-space characters.

Since displaying the form and processing the form submission ‘requires’ a logged in user, you should have a login test above the post method form processing code. If there isn’t a logged in user, that’s an error and you would setup and display a message telling the visitor that they must be logged in to access the page. This would serve as validation that there is a value in the session variable.

Next, the posted code implies that the form processing code is after the form. This will make it hard to display any user/validation errors, repopulate the form field values with the submitted data if there should be any errors, when you redisplay the form. The code on your page should be laid out in this general order -

  1. Initialization.
  2. Post method form processing code.
  3. Get method business logic - code to get/produce data needed to display the page.
  4. Html document.

Next, you always need error handling for statements that can fail. For database statements that can fail - connection, query, prepare, and execute, the simplest way of adding error handling, without adding code at each statement is to use exceptions for errors and in most cases simply let php catch and handle the exception, where php will use its error related settings to control what happens with the actual error information (database statement errors will ‘automatically’ get displayed/logged the same as php errors.) It’s likely that you are getting a database error concerning the session variable being a null value. Having error handling will tell you if and why a database statement is failing. To enable exceptions for errors for the mysqli extension, add the following line of code before the point where you make the database connection -


Lastly, this query can probably result in duplicate data, such as if the same task/employee is entered more than once or perhaps even the task should be unique? This should result in an error. The way to accomplish this is to define unique indexes for the column(s) or unique composite indexes for combined columns that must contain unique values. If you attempt to insert duplicate data, a duplicate index error will result. This is the exception to letting php catch database exceptions. For insert/update queries that could result in duplicate (or out of range values), your code would catch the database exception, test if the error number is for something that your code is designed to handle. then setup a message telling the visitor exactly what was wrong with the data that they submitted. For all other error numbers, just re-throw the exception and let php handle it.

1 Like

Thank youuu soooooo much for your advice I added the error handling statement you gave it displayed an error so i have something to atleast go on.

The error i got was Cannot add or update a child row: a foreign key constraint fails (workmanagement.tasks, CONSTRAINT tasks_ibfk_1 FOREIGN KEY (eid) REFERENCES employee. What I dont get is that I logged in through a user that I had registered to the system so this error telling me that there is no matching row in the other table is weird because that persons details show up in the employee table. The employees ID is 1 and Id tried echoing the session ID using ‘echo session_id();’ so id know if it was actually working and it echoed 6l2m88r0334sga5cpjj4u5rf40. Im assuming that would hold the persons ID? Should i take it that the session variable carries the data and isnt empty?

If it isnt empty, I assume that there is something that i have done wrong when it comes to inserting the session value part. Because the database recorded my entry when i got the user to add their IDs manually. The database wont let me insert anything at all if the foreign key value is not being added in. So maybe ive called the session variable in the insert statement incorrectly? Do you see any code errors there? Or do you know of any materials i can check out that would help me manipulate the session variable?

session_id() is the internal PHP reference for the session overall (doc: ) , you are looking for $_SESSION['login_employee'], aren’t you? What happens when you echo that, or $id in your code?

Where do you create that session variable? If you var_dump($_SESSION); at the start of your code, what do you see?

1 Like

i get array(1) { ["login_employee"]=> string(14) "" } when i add what you suggested

Sorry im not sure what happening on this site either my post is hidden or its my internet connection. I get array(1) { ["login_employee"]=> string(14) "" } when i insert your suggestion.

You need to ensure you format code as code, or the presence of an e-mail address will trigger the anti-Spam measures.

(Also, you don’t want to expose a genuine email addresses on a public forum.)

1 Like

A. Don’t use an email address as the value that relates data between tables. Use the autoincrement primary index from the parent table.
B. The reason this is failing is because you are telling php to treat the value as an integer in the insert query, which for a non-numeric string, will be a zero. The reason for the error, when using an email address/string, is the ‘i’ in the ‘sssi’ format string -

$stmt->bind_param('sssi', $name, $datep, $datef, $id);

The solution is to use the autoincrement primary index from the user table.

1 Like

I figured it outttttt. I was expecting it to be carrying the employee ID so when i set the foreign key it was set to accept the employee id instead of a gmail address. After I ran your code I figured it was carrying the mail address and I made that the foreign key instead. It finally rannnn. Very silly mistake on my part so sorry for the hassle. But thank you for the help or I wouldnt have known what the variable was carrying. Have a nice dayyyy.

I guess it automatically carried the gmail value in the session instead of the ID since the user inserts their gmail and password to login. I thought it would automatically refer its primary key to identify. If i wanted it to carry their ID instead I would have to set it to accept their ID and password to login right?

It doesn’t automatically do that - it’s just whatever your code is doing.

No. You could use the same login form, then in your login validation code, use the email address to retrieve the employee ID from the database, and store that in the session variable.

1 Like

Ohh okay. Il do that with mine then. Thanks for the tips!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.