提交表单后立即回显新生成的(自动递增)用户 ID?

问题描述 投票:0回答:1

我的用户在表单中提交一些基本信息后,我如何让新创建的用户 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>
php html forms mysqli echo
1个回答
2
投票

使用

$conn->insert_id
检索值并将其传递到查询字符串中或将其设置到会话中。

此外,无论您遵循的是什么教程或指南,都已经严重过时或非常糟糕。使用 prepared statements 并遵循 good tutorial

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

在二级页面上,您将使用查询参数

<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'];
© www.soinside.com 2019 - 2024. All rights reserved.