通过表单执行 SQL 插入时填充会话用户 ID

Populate Session UserID whilst doing a SQL insert via a form

我想记录当前登录用户的用户 ID,该用户将数据输入到表单中,然后将其记录到数据库中 table

目前插入查询是 运行 并更新除用户 ID 之外的所有内容..用户 ID 变量肯定有效,因为我能够在同一页面上毫无问题地回显它

代码如下;

$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();

        }
}

session_start() 添加到顶部,一切正常。