提问人:DarthCoder 提问时间:3/20/2023 更新时间:3/20/2023 访问量:75
在表单提交后立即回显新生成的(自动递增)用户 ID?
Echo back a newly generated (auto increment) user id immediately after form submission?
问:
我的用户在表单中提交一些基本信息后,如何让新创建的用户 ID 回显回标题(重定向)页面上的隐藏字段?
第一种形式包含基本姓名、电话、电子邮件输入。当用户提交表单(到数据库)时,AI 的“userID”列会生成其唯一的“userID”。
我需要该唯一 ID 回显回标题(重定向)页面上的隐藏字段,然后用户将在该字段上传他们的个人资料照片。
新用户表单:
<h1>New User Form</h1>
<form action="newUser_formHandler.php" method="POST" >
<input name="userName" placeholder="Enter Name"><br><br>
<input name="userPhone" placeholder="Enter Phone"><br><br>
<input name="userEmail" placeholder="Enter Email"><br><br>
<input type="submit" name="submit" value="Submit">
</form>
新的用户表单处理程序:
<?php include './secure/dbKey.php';?>
<?php
if(isset($_POST['submit'])){
$userName = $_POST['userName'] ;
$userPhone = $_POST['userPhone'] ;
$userEmail = $_POST['userEmail'] ;
$newUser = "insert into Users (userName, userPhone, userEmail)
values('$userName', '$userPhone', '$userEmail')";
$run = mysqli_query($conn,$newUser) or die(mysqli_error()) ;
//Page Re-direct after form submission
header('location: /profilePhoto_UploadPage.php');
}
?>
个人资料照片上传页面:
<?php include './secure/dbKey.php';?>
<html>
<head>
<title>Profile Photo Upload Page</title>
</head>
<body>
<h1>Congratulations!</h1>
<h2>Your profile was succesfully created!</h2>
<a>Please upload a photo to complete your profile:</a><br><br>
<form action="photoUpload_Handler.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="userID" id="userID" value="<?php echo $userID; ?>">
<input type="file" name="fileToUpload" id="fileToUpload"><br><br>
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
答:
4赞
Phil
3/20/2023
#1
使用 $conn->insert_id
检索值,并将其传递到查询字符串中或将其设置到会话中。
此外,您遵循的任何教程或指南都严重过时或非常糟糕。使用准备好的语句并遵循一个好的教程
$stmt = $conn->prepare(
"INSERT INTO `Users` (`userName`, `userPhone`, `userEmail`) VALUES (?, ?, ?)"
);
$stmt->bind_param(
"sss",
$_POST["userName"],
$_POST["userPhone"],
$_POST["userEmail"]
);
$stmt->execute();
header(
"Location: /profilePhoto_UploadPage.php?" .
http_build_query(["userID" => $conn->insert_id])
);
exit();
在辅助页面上,您将使用 query 参数
<input
type="hidden"
name="userID"
id="userID"
value="<?= htmlspecialchars($_GET['userID']) ?>"
/>
使用会话同样简单
session_start();
// same mysqli code as above
$_SESSION['userID'] = $conn->insert_id;
header('Location: /profilePhoto_UploadPage.php');
exit;
在辅助页面上,您实际上并不需要它,因为您发布到的任何页面都可以阅读会话
// photoUpload_Handler.php
session_start();
$userID = $_SESSION['userID'];
评论
how do I get the newly created userID
mysqli_error()
将不起作用,因为此版本需要数据库连接。您也不应将错误抛出控制台。记录它们并查看您的日志。mysqli_*