从另一个PHP文件中检索数据

时间:2019-04-14 12:33:21

标签: php mysql

用户登录后,我一直试图将数据从一个php文件传递到另一个php文件。

目标是当用户注册要重定向到另一个页面上显示其统计信息(用户名,金钱,红宝石,钻石)。

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>

请检查我的代码并帮助我。 我已经尝试了很长时间,以至于我觉得自己会失去理智。 我认为php中存在错误。

1 个答案:

答案 0 :(得分:1)

除非您没有在答案中显示任何内容,否则您实际上并没有采取任何措施来保存会话数据。

<div>

在这里,通过传递标头,您正在执行客户端重定向,从而导致新请求发送到您的服务器。这意味着在请求1(... 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'); ... )中设置的变量将在请求2(index.php)中不可用。

您可能不想为这样简单的事情进行客户端重定向。无需重组代码即可解决此问题的最简单方法是将标头调用更改为包含

index2.php

(实际上不这样做,请参见下面的更新)。

但是,您可能想考虑如何组织代码。到处拨打... while($row = mysqli_fetch_assoc($resultsThree)){ $username = $_SESSION['username']; $level = $row['level']; $money = $row['money']; $diamond = $row['diamond']; $ruby = $row['rubin']; } include('index2.php'); ... 的电话会很快变得混乱和混乱。我建议研究一下PHP路由库。周围有一些,例如Klein

最后,如果由于某种原因您确实需要跨客户端重定向保留数据,则需要将其存储在会话变量或数据库中。您从中获取用户名的include数组是读/写的,您可以在其中存储应在整个会话中保留的数据(注意事项。请在适当时使用数据库或文件存储)。请参阅more information.

的PHP文档

更新

因此,我刚刚注意到您实际上是在index2.php文件中$_SESSION; include文件中。在这种情况下,您无法在server.php文件中server.php include文件,因为它将是一个无限循环。

我不确定推荐什么,但是似乎您需要重组代码,同时要记住使用index2.php调用进行重定向会丢失所有当前的PHP状态(变量等)。最简单的事情可能是只调用您的header文件,让它包含您的服务器文件,如果有错误,则然后调用index2.php。成功执行查询后,您的变量将可用。

因此,在die中:

server.php