简体   繁体   中英

Creating a new user and trying to get the user_id for session id but getting first id PHP

I'm trying to fix my sign up in PHP, when I create a new user my user id instantly becomes the first one available, if I have 100 users and I create a new one the user id should be 101 which it is on the database but on my session it becomes 1, if I delete the first user and the only user available has the id of 2 it becomes 2. What is wrong in my code? Cant seem to debug it.

<?php 

    $username = $_POST['username'];
    $email =  $_POST['email'];
    $pass = $_POST['pass'];
    $pass2 = $_POST['pass2'];


    $con = mysqli_connect("localhost", "root", "", "smarttime");
    $query = mysqli_query($con,"INSERT INTO users (use_name, use_email, use_pass) values ('$username', '$email', '$pass')");

    $test = mysqli_query($con,"SELECT * from users");

    $row = mysqli_fetch_array($test); 


    if(empty($username) || empty($pass) || empty($email) || empty($pass2))
    {
        header("Location:signup.php");
    }else{
        if($row['use_email'] == $email){
                    header("Location:login.php");
        }else{
                $query;
                session_start();
                $_SESSION['user_id'] = $row['use_id'];
                $_SESSION['nome'] = $row['use_name'];
                header('Location:logged.php');
                exit();

        }
    }

 ?>

html

<!DOCTYPE html>

<html lang="en">





  <head>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>SmartTime</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css\main.css" rel="stylesheet">

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>



  <body>  

      <nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" >SmartTime</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarText">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="index.php">Home <span class="sr-only">(current)</span></a>
      </li>
    </ul>
    <span class="navbar-text">
    <a href="/login.php" >Login</a>&emsp;
    <a href="/signup.php" >Sign Up</a>
    </span>
  </div>
</nav>

    <div class="container">
        <div class="card card-container">
            <!-- <img class="profile-img-card" src="//lh3.googleusercontent.com/-6V8xOA6M7BA/AAAAAAAAAAI/AAAAAAAAAAA/rzlHcD0KYwo/photo.jpg?sz=120" alt="" /> -->
            <img id="profile-img" class="profile-img-card" src="images/Doge.png" />
            <p id="profile-name" class="profile-name-card"></p>
            <form action="validatesignup.php" method="post" class="form-signin">
                <span id="reauth-email" class="reauth-email"></span>
                <input type="text" id="inputEmail" class="form-control" name="username" placeholder="Username" required>
                <input type="email" id="inputEmail" class="form-control" name="email" placeholder="Email address" required>
                <input type="password" id="inputPassword" class="form-control" name="pass" placeholder="Password" required>
                <input type="password" id="inputPassword" class="form-control" name="pass2" placeholder="Confirm Password" required>
                <button class="btn btn-lg btn-primary btn-block btn-signin" type="submit">Login</button>
            </form><!-- /form -->
            <a href="login.php" class="forgot-password">
                Already have an account? Sign in!
            </a>
        </div><!-- /card-container -->
    </div><!-- /container -->

    </body>
  </html>

new code

<?php 

    $username = $_POST['username'];
    $email =  $_POST['email'];
    $pass = $_POST['pass'];
    $pass2 = $_POST['pass2'];


    $con = mysqli_connect("localhost", "root", "", "smarttime");

    // Insufficient input
    if(empty($username) || empty($pass) || empty($email) || empty($pass2)) {
        header("Location:signup.php?msg=please+fill+all");
    } else {
        $stmt_email_test = mysqli_prepare($con, 'SELECT use_email FROM users WHERE use_email=?');
        $stmt_email_test->bind_param('s',$email); // 's' for one string
        $stmt_email_test->execute();
        $stmt_email_test->bind_result($email_test);

        if($email_test != null) { // Email exists
            header("Location:login.php");
        } else if( $pass != $pass2 ) { // Check if password repetition is ok
            header("Location:signup.php?msg=passwords+do+not+match");
        } else { // Everything is fine, do insert and fill session
            $stmt = mysqli_prepare($con, "INSERT INTO users (use_name, use_email, use_pass) values (?,?,?)");
            var_dump($stmt->error);
            $stmt->bind_param('sss', $username, $email, $pass); // 'sss' for 3 strings
            $stmt->execute();


            // Get the new user_id
            $new_user_id = mysql_insert_id();

            // Fill Session
            $_SESSION['user_id'] = $new_user_id;
            $_SESSION['name'] = $username;
            header('Location:logged.php');
            exit();

        }
    }

 ?>

Use mysqli_insert_id to get last id and use in select query, like this:-

$query = mysqli_query($con,"INSERT INTO users (use_name, use_email, use_pass) values 
('$username', '$email', '$pass')");
$id = mysqli_insert_id($con);

$res = mysqli_query($con,"SELECT * from users WHERE user_id={$id}");
if($row = mysqli_fetch_assoc($res)) {
 $_SESSION['user_id'] = $row['user_id'];
}

I've made a prepared-statement version. You should use prepared statements to prevent sql-injections have a look at mysqli_prepare

Furthermore, I highly recommend to NOT store the password as plain text. Php offers a easy and safe way to store passwords: password_hash and password_verify is all you will need:)

<?php

// Insufficient input
if (empty($_POST['username']) || empty($_POST['pass']) || empty($_POST['email']) || empty($_POST['pass2'])) {
    header("Location:signup.php?msg=please+fill+all");
    exit;
}

$username = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect("localhost", "root", "", "smarttime");

$stmt_email_test = $con->prepare('SELECT email FROM users WHERE email=?');
$stmt_email_test->bind_param('s', $email); // 's' for one string
$stmt_email_test->execute();
$stmt_email_test->bind_result($email_test);
$stmt_email_test->close();

if ($email_test !== null) { // Email exists
    header("Location:login.php");
    exit();
}
if ($pass !== $pass2) { // Check if password repetition is ok
    header("Location:signup.php?msg=passwords+do+not+match");
    exit();
}

// Everything is fine, do insert and fill session
$stmt = $con->prepare("INSERT INTO users (name, email, pass) values (?,?,?)");
$stmt->bind_param('sss', $username, $email, $pass); // 'sss' for 3 strings
$stmt->execute();

// Get the new user_id
$new_user_id = $stmt->insert_id;
$stmt->close();

// Fill Session
session_start();
$_SESSION['user_id'] = $new_user_id;
$_SESSION['name'] = $username;
header('Location:logged.php');
exit();

Try adding this code in you first else condition-

$sql = "SELECT user_id FROM users WHERE email = '".$email."' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // store the user_id of the person newly registered to $_SESSION['user_id]
    while($row = $result->fetch_assoc()) {
        $_SESSION['user_id] = $row["user_id"];
    }
    header('Location:dashboard.php');
} else {
    echo "No user found!";
}

Hope that helps!

$test = mysqli_query($con,"SELECT * from users");

In this line you have to pass the email or email & password to get the corresponding id

$test = mysqli_query($con,"SELECT * from users where use_email = ".$email);

It will work for you.. just add where condition to that query to retrieve particular user details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM