我想记录当前登录用户的用户ID,该用户将数据输入表单,然后将其记录到数据库表中
目前,插入查询正在运行并更新除用户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();
}
}
答案 0 :(得分:0)
在顶部添加session_start()
,一切正常。