php - 从另一个 php 文件中检索数据

标签 php mysql

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

目标是当用户注册时被重定向到显示其统计信息的另一个页面(用户名、金钱、 ruby 、钻石)。

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>

服务器.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 中有一个错误。

最佳答案

除非您没有在答案中显示某些内容,否则您实际上并没有做任何事情来保留 session 数据。

...
    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');
...

在这里,通过传递 header ,您将执行客户端重定向,从而将新请求发送到您的服务器。这意味着请求 1 (index.php) 中设置的变量在请求 2 (index2.php) 中不可用。

您可能不想为如此简单的事情进行客户端重定向。在不重组代码的情况下解决此问题的最简单方法是更改​​ header 调用以包含

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

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

但是,您可能需要考虑如何组织代码。到处都有 include 调用很快就会变得困惑和困惑。我建议研究一下 PHP 路由库。周围有几个,比如Klein .

最后,如果由于某种原因您确实需要在客户端重定向中保留数据,则需要将其存储在 session 变量或数据库中。您从中获取用户名的 $_SESSION; 数组是读/写的,您可以在其中存储应该在整个 session 中持续存在的数据(有警告。在适当的时候使用数据库或文件存储)。请参阅 PHP 文档 more information.

更新:

所以我刚刚注意到您实际上是在您的index2.php 文件中include您的server.php 文件。在这种情况下,您不能在 server.php 文件中包含 index2.php 文件,因为这将是一个无限循环。

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

因此,在 server.php 中:

if (count($errors) == 0) {
   ....
} else {
  die('Unsuccessful registration');
}

关于php - 从另一个 php 文件中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55675297/

相关文章:

c# - 将自定义 .NET ORM 迁移到 Entity Frame/Dapper

php - 如何使用 PDO 从 href 链接获取单行,收到 fatal error : Call to a member function prepare() on a non-object?

mysql - 无服务器离线 lambda 到主机数据库的连接被拒绝

php - MySQL 查询 WordPress 日事件

php - 如何将xhtml表单与php代码结合起来?

php - 如何使用 php 和 MySQL 将表的整个数组数据插入到新表中

php - 连接 html、javascript、php 和 mysql

PHP:将前缀字符串添加到数组值

javascript - 您可以根据屏幕大小选择包含和脚本吗?

php - 操作状态与异常