MySQL PHP匹配用户ID在创建" USER"

时间:2016-11-29 17:13:17

标签: php mysql

我正在编写一个社交媒体网站"对于一个班级项目,我在一个部分遇到了麻烦。

首次注册帐户时,用户必须输入用户名和密码,然后单击“提交”按钮。 PHP代码检查输入以确保它们全部有效并且不会有任何重复,如果一切都通过,它会将用户名和密码添加到名为" users"的SQL表中。用户有3列:用户名,密码和用户ID。 userID是主键。

完成该过程后,我们会重定向到一个单独的页面,用户可以在其中输入更多个人信息,例如名字和姓氏,城市,国家等。此表格称为" userInfo"具有列:firstName,lastName,emailAddress,address,city,country和userID。 userID再一次是主键。

我想弄清楚的是如何在insert语句中匹配两个用户ID。我有一个收集所有必需信息的表单,但我不知道如何设置SQL查询以确保users.userID与userInfo.userID匹配。

这是我的用户PHP(初始注册)

<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";

if(isset($_POST['submit'])){
    // Get inputs
    $username = $_POST['user'];
    $password = $_POST['password'];

    // Clean inputs and encrypt password
    $username = mysqli_real_escape_string($conn, $username);
    $password = mysqli_real_escape_string($conn, $password);
    $password = md5($password);

    // Check username not empty
    if (empty($username)) {
        $error = "true";
        $errorMessage = "Please enter a value for your username";
    }

    // Check username does not already exist
    $checkUserQuery = "SELECT username FROM users WHERE username = '$username'";
    $checkResult = $conn->query($checkUserQuery);
    if($checkResult->num_rows > 0) {
        $error = "true";
        $errorMessage = "This username already exists";
    }

    // Username does not exist, add to database
    else {
        $insertUserQuery = "INSERT INTO users (username, password) VALUES('$username', '$password')";
        $insertResult = $conn->query($insertUserQuery);
        $_SESSION['username'] = $username;
        header("Location: userInfo.php");
    }
  }
?>

到目前为止,这是我用于userInfo的PHP代码:

<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";

$username = $_SESSION['username'];

if(isset($_POST['submit'])){
    // Get inputs
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $emailAddress = "fakeEmailAddress@fakeyfakefake.com";
    $address = $_POST['address'];
    $city = $_POST['city'];
    $country = $_POST['country'];

    // Clean inputs
    $firstName = mysqli_real_escape_string($conn, $firstName);
    $lastName = mysqli_real_escape_string($conn, $lastName);
    $address = mysqli_real_escape_string($conn, $address);
    $city = mysqli_real_escape_string($conn, $city);
    $country = mysqli_real_escape_string($conn, $country);

    // Validate Inputs (Only validating first and last name, location entries are not required)

    if(empty($firstName) || empty($lastName)) {
        $error = "true";
        $errorMessage = "Please enter your first AND last name";
    }

    else {

    }
  }
?>

道歉,如果这是超级凌乱。数据库不是我的强项lol。

非常感谢能够提供帮助的任何人!

1 个答案:

答案 0 :(得分:2)

您需要将mysqli_insert_id插入到users表中并将其传递(可能通过$ _SESSION)以便在userInfo中创建。