Search code examples
phpsqlsession-variables

Populate Session UserID whilst doing a SQL insert via a form


I want to record the user ID from the current logged in user who enters data into the form which in turn is recorded to a database table

At present the insert query is running and updating all but the user id..the user id variable is definitely working as I am able to echo it out without any issues on the same page

Code is as follows;

$barcode = $_POST['barcode'];
  $weight = $_POST['weight'];
  $userId = $_SESSION['userId'];

//error handling begins

  // check for any empty inputs.
  if (empty($barcode) || empty($weight)) {
    header("Location: ../record.php?error=emptyfields&barcode=".$barcode."&weight=".$weight);
    exit();
  }
  //we check if valid barcode entered. In this case ONLY letters and numbers.
  else if (!preg_match("/^[a-zA-Z0-9]*$/", $barcode)) {
    header("Location: ../record.php?error=invalidbarcode&barcode=".$weight);
    exit();
  }
  // check for an invalid weight. In this case ONLY numbers.
  else if (!preg_match("/^[0-9].*$/", $weight)) {
    header("Location: ../record.php?error=invalidweight&barcode=".$barcode);
    exit();
  }
  else {

        $sql = "INSERT INTO trimrecords (barcode, weight, createdby) VALUES (?,?,?);";
        // initialize a new statement using the connection from the dbh.inc.php file.
        $stmt = mysqli_stmt_init($conn);
        //  prepare  SQL statement AND check if there are any errors with it.
        if (!mysqli_stmt_prepare($stmt, $sql)) {
          // If there is an error send the user back to the record page.
          header("Location: ../record.php?error=sqlerror");
          exit();
        }
        else {

          // If there is no error continue the script!

          // bind the type of parameters we expect to pass into the statement, and bind the data from the user.
          mysqli_stmt_bind_param($stmt, "ssi", $barcode, $weight, $userId);
          // execute the prepared statement and send it to the database!
          // data is registered to Db at this stage
          mysqli_stmt_execute($stmt);
          // send back with success
          header("Location: ../record.php?record=success");
          exit();

        }
}

Solution

  • Add session_start() to the top and all worked.