【问题标题】:session store only one item in array会话仅在数组中存储一项
【发布时间】:2021-06-21 15:07:43
【问题描述】:

我是 php 新手,我有一个注册表单,我想将注册的用户存储在数组或 JSON 中, 我建立了用户类,当我注册一个新用户时,我想将它添加到这个数组或 JSON 中,但是会话数组只接受一个用户,当我添加新用户会话时删除旧用户并存储新用户! 这是我的代码:

class User
{
        private $id;
        private $first_name;
        private $last_name;
        private $email;
        private $password;
    
        public function register($id, $firstName, $lastName, $email, $password)
        {
            $this->id = $id;
            $this->first_name = stripslashes($firstName);
            $this->last_name = stripslashes($lastName);
            $this->email = $email;
            $this->password = password_hash($password, PASSWORD_DEFAULT);
        }
    }



class DB
{
    public $users;

    public function __construct()
    {
        $this->users = [];
    }
}


<?php
$counter = 0;
$_SESSION['usersDB'] = new DB;

if (isset($_POST['submit'])) {
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $user = new User;
    $user->register(++$counter, $firstName, $lastName, $email, $password);
    array_push($_SESSION['usersDB']->users, $user);
}
echo '<pre>';
var_dump($_SESSION['usersDB']);
echo '</pre>';
?>

我应该怎么做才能将所有用户存储在一个地方?

【问题讨论】:

  • $_SESSION['usersDB'] = new DB; 将在调用时创建一个新的空数据库。 $_SESSION['usersDB'] 中的任何先前值都将丢失。
  • @Progman 如何解决它并创建一次数据库
  • 真的不确定这是否明智,但您需要一个数组来容纳多个用途,所以array_push($_SESSION['usersDB']-&gt;users[], $user);

标签: php


【解决方案1】:

每次运行脚本时,您都将会话变量替换为new DB。如果会话变量已设置,则不应这样做。

if (!isset($_SESSION['userdDB'])) {
    $_SESSION['usersDB'] = new DB;
}

此外,$counter 将始终为 1,因为您在脚本的开头设置了 $counter = 0;。您可以将其保存在会话变量中,但实际上没有必要。您可以使用:

$counter = count($_SESSION['usersDB']->users);

我不确定这是否能满足您的需求。每个浏览器会话都有自己的会话变量,因此每个用户将只有一个他们已注册的用户列表。会话变量也是临时的,所以它不是一个永久保存注册用户列表的好方法。

保存永久用户列表的正确方法是在服务器上的数据库中。

【讨论】:

  • 你好,这个计数器不是会话数据库,它是用户对象 ID,我在我的代码中做了这个,但它不起作用。我还是有同样的问题
  • 但是所有用户都会得到对象 ID = 1。
  • 好的,我同意这一点,但是我可以在不使用 mySQL 的情况下将所有用户存储在我的应用程序中的方式是什么
  • 会话是错误的。
【解决方案2】:

cookiesserializeunserialize 功能结合使用

user.php

<?php
class User
{
    public static $cnt = 0;
    private $id;
    private $name;
    public function __construct($name='')
    {
        self::$cnt++;
        $this->id = self::$cnt;
        $this->name = stripslashes($name);
    }
    public function __get($name){
        return $this->$name;
    }
    public function __set($name,$val){
        $this->$name = stripslashes($val);
    } 

    public function __toString(){
        return 'user('.$this->id.", ".$this->name.")";
    }
}
?>

db.php

<?php
class DB
{
    public $users = [];
    public function __construct()
    {
        $this->users = [];
    }

    public function __toString()
    {
        $str = "<ul>";
        foreach ($this->users as $user)
            $str .="<li>".$user."</li>";
        $str .= "</ul>";
        return $str;
    }
}
?>

index.php

<?php
require_once('user.php');

$user1 = new User('Steve');
$user2 = new User('Everst');

require_once('db.php');
$databse = new DB();

$databse->users[] = $user1;
$databse->users[] = $user2;

setcookie('users', serialize($databse),time() + 3600,"/","",0);
echo $_COOKIE['users'];
?>

users.php

<?php
require_once('db.php');
require_once('user.php');
$databse = unserialize($_COOKIE['users']);
echo $databse;
?>

【讨论】:

    【解决方案3】:

    sessionJSON

    结合使用
    1. 实现接口JsonSerializable
    2. 重写方法jsonSerialize

    user.php

    <?php
    class User implements JsonSerializable
    {
        public static $cnt = 0;
        private $id;
        private $name;
        public function __construct($name='')
        {
            self::$cnt++;
            $this->id = self::$cnt;
            $this->name = stripslashes($name);
        }
        public function __get($name){
            return $this->$name;
        }
        public function __set($name,$val){
            $this->$name = stripslashes($val);
        } 
    
        public function __toString(){
            return 'user('.$this->id.", ".$this->name.")";
        }
    
        public function jsonSerialize() {
            return array(
                 'id' => $this->id,
                 'name' => $this->name
            );
        }
    }
    ?>
    

    index.php

    <?php
    session_start();
    
    include('user.php');
    include('db.php');
    
    $user1 = new User('Steve');
    $user2 = new User('Everst');
    $databse = new DB();
    $databse->users[] = $user1;
    $databse->users[] = $user2;
    
    $_SESSION['database'] = JSON_encode($databse);//{"users":[{"id":1,"name":"Steve"},{"id":2,"name":"Everst"}]}
    
    ?>
    

    users.php

    <?php
    session_start();
    $databse = json_decode($_SESSION['database']);
    foreach ($databse->users as $user)
        echo $user->id." - ".$user->name."<BR>";
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-23
      • 2018-12-09
      • 2017-12-21
      相关资源
      最近更新 更多