0

I've been trying to pass data from one php file to another php file after the user login.

The goal is when a user registers to be redirected to another page where his statistics are displayed(username, money, ruby, diamond).

index.php

<?php include('server.php') ?>
<?php include('errors.php'); ?>

<div class="form-popupRegister" id="myRegForm">
    <form method="post" action="server.php" class="form-containerReg">

        <h1>Регистрирация</h1>

        <label for="username"><b>Име</b></label>
        <input type="text" name="username" placeholder="Въведете името на лейдито" value="<?php echo $username; ?>">


        <label for="email"><b>Е-майл</b></label>
        <input type="text" name="email" placeholder="Въведете e-mail" value="<?php echo $email; ?>">


        <label for="password_1"><b>Парола</b></label>
        <input type="password" placeholder="Въведете парола" name="password_1">


        <label for="password_2"><b>Повторете Парола</b></label>
        <input type="password" placeholder="Въведете парола повторно" name="password_2">


        <button type="submit" class="btnReg" name="reg_user">Register</button>
        <button type="button" class="btn-cancelReg" onclick="closeRegForm()">Close</button>
    </form>
</div>

server.php

<?php
session_start();

// initializing variables
$username = "";
$email    = "";
$level = "";
$money = ""; 
$diamond = "";
$ruby = "";
$errors = array(); 
$ID = "";
$row = "";

// connect to the database
$db = mysqli_connect('localhost', 'id9159890_uregisterdb', 'testdb', 'id9159890_registerdb');

// REGISTER USER
if (isset($_POST['reg_user'])) {
  // receive all input values from the form
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $email = mysqli_real_escape_string($db, $_POST['email']);
  $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);

  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array
  if (empty($username)) { array_push($errors, "Username is required"); }
  if (empty($email)) { array_push($errors, "Email is required"); }
  if (empty($password_1)) { array_push($errors, "Password is required"); }
  if ($password_1 != $password_2) {
    array_push($errors, "The two passwords do not match");
  }

  // first check the database to make sure 
  // a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM register WHERE username='$username' OR email='$email' LIMIT 1";
  $result = mysqli_query($db, $user_check_query);
  $user = mysqli_fetch_assoc($result);

  if ($user) { // if user exists
    if ($user['username'] === $username) {
      array_push($errors, "Username already exists");
    }

    if ($user['email'] === $email) {
      array_push($errors, "email already exists");
    }
  }

  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
    $password = md5($password_1);//encrypt the password before saving in the database

    $query = "INSERT INTO register (username, email, password) 
              VALUES('$username', '$email', '$password')";
    mysqli_query($db, $query);
    $_SESSION['username'] = $username;
    $queryTwo="SELECT ID FROM register WHERE username='$username'";
    $results = mysqli_query($db, $queryTwo);
    $resultsTwo = mysqli_fetch_assoc($results);
    $ID = $resultsTwo['ID'];
    $queryInsert="INSERT INTO mainuserdata (ID, money, diamond, rubin, level)
    VALUES ('$ID', '0', '0', '0', '0')";
    mysqli_query($db, $queryInsert);
    $queryThree="SELECT * FROM mainuserdata WHERE ID='$ID'";
    $resultsThree = mysqli_query($db, $queryThree);

    while($row = mysqli_fetch_assoc($resultsThree)){
        $username = $_SESSION['username'];
        $level = $row['level'];
        $money = $row['money'];
        $diamond = $row['diamond'];
        $ruby = $row['rubin'];
    }
    header('location: index2.php');
  }else{
    echo 'Unsuccessful registration!';
  }
}

index2.php

<?php require('server.php') ?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title>PwettyKittyPincesa</title>

  <link href="./style.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <div class="navWrapper">
        <div class="statistics">
            <div class="profilePicture" name="profilePicture">
                <label class="profilePictureLabel" for="profilePicture"><b><?php echo $username; ?></b></label>
            </div>

            <div class="money" name="money">
            <output name="money" for="money"><?php echo $money; ?></output>
            </div>

            <div class="diamond" name="diamond">
                <label class="diamondLabel" for="diamond"><b><?php echo $diamond; ?></b></label>
            </div>

            <div class="ruby" name="ruby">
                <label class="rubyLabel" for="ruby"><b><?php echo $ruby; ?></b></label>
            </div>

            <div class="level" name="level">
                <label class="levelLabel" for="level"><b>Level:<?php echo $level; ?></b></label>
            </div>
        </div>
    </div>
</body>
</html>

Please, check out my code and help me out. I've been trying for so long that I feel that I'm about to lose my sanity. I think there is a bug in php.

2
  • 1
    after redirecting user to another page the previous variables are gone. either store them in session or query them from db Commented Apr 14, 2019 at 12:40
  • "I think there is a bug in {CHOOSE_YOUR_LANGUAGE}" -- I've heard so many undergrads saying things like this :) Commented Apr 14, 2019 at 14:07

1 Answer 1

1

Unless you've not shown something in your answer you're not actually doing anything to persist your session data.

...
    while($row = mysqli_fetch_assoc($resultsThree)){
        $username = $_SESSION['username'];
        $level = $row['level'];
        $money = $row['money'];
        $diamond = $row['diamond'];
        $ruby = $row['rubin'];
    }
    header('location: index2.php');
...

Here, by passing a header, you're doing a client side redirect that causes a new request to be sent to your server. This means that the variables that are set within request 1 (index.php) aren't going to be available in request 2 (index2.php).

You probably don't want to do a client side redirect for such a simple thing. The simplest way to fix this without restructuring your code is to change your header call to include

...
    while($row = mysqli_fetch_assoc($resultsThree)){
        $username = $_SESSION['username'];
        $level = $row['level'];
        $money = $row['money'];
        $diamond = $row['diamond'];
        $ruby = $row['rubin'];
    }
    include('index2.php');
...

(Actually don't do this, see update below).

However you probably want to think about how you are organising your code. Having include calls all over the place can quickly get messy and confusing. I'd suggest looking into a PHP routing library. There are a few around, such as Klein.

Finally if you do need to persist data across a client side redirect for some reason you will need to store this in a session variable or in the database. That $_SESSION; array you fetched your username from is read / write and you can store data in it that should persist across the session (with caveats. Use database or file storage when appropriate). See the PHP docs for more information.

Update:

So I just noticed that you are actually includeing your server.php file in your index2.php file. In this case you can't include the index2.php file in the server.php file as it will be an infinite loop.

I'm not sure what to recommend but it seems you need to restructure your code while bearing in mind that redirecting using a header call you will lose all your current PHP state (variables etc). The simplest thing would probably be to just call your index2.php file, let it include your server file and then die if there are errors. Your variables will be available if it successfully executes the query.

So, within server.php:

if (count($errors) == 0) {
   ....
} else {
  die('Unsuccessful registration');
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.