doujie9252 2013-05-21 12:10
浏览 47
已采纳

从同一列的数据库序列化多个数据

I'm new to PHP and using serialized data,

I have a Database which has a 2 tables, user & character. characterId has a relation with userId.

An user has 2 characters, so I wanted to get the data with the following code:

public static function getCharacter() {
        $mysqli = Controller_Core_Config::getDB();
        if ($mysqli != null) {
            $user = unserialize($_SESSION['user']);
            $sql = "SELECT * FROM `character` WHERE `userId`='" . $user->getId() . "'";
            $result = $mysqli -> query($sql);

            if ($result !== FALSE && $result -> num_rows > 0) {
                $row = $result -> fetch_assoc();
                $_SESSION["character"] = serialize(new Model_Game_User(
                    $row['characterId'], 
                    $row['characterName'], 
                    $row['userId'], 
                    $row['level']
                    ));
            } else {
                echo "You have no characters.";
            }
        }
    }

And If I wanted to show the data I use the following code:

//some code
$character = unserialize($_SESSION["character"]);
$output .= $character->getCharacterName() . "<br>";
//some code

My problem is, that when I var_dump the ($_SESSION["character"]) I get only 1 character:

string(202) "O:15:"Model_Game_User":4:{s:28:"Model_Game_UsercharacterId";s:1:"3";s:30:"Model_Game_UsercharacterName";s:9:"adminious";s:23:"Model_Game_UseruserId";s:1:"2";s:22:"Model_Game_Userlevel";s:1:"3";}"

And my question is, is it possible to have multiple 'characters' in serialized data?

  • 写回答

1条回答 默认 最新

  • douxie3625 2013-05-21 12:15
    关注

    You are not looping over your results. You are just adding the first result found into the session

    You would need something like this to replace you if block:

    if ($result !== FALSE && $result -> num_rows > 0) {
        $_SESSION["character"][] = array();
        while($row = $result -> fetch_assoc()) {
            $_SESSION["character"][] = serialize(new Model_Game_User(
                $row['characterId'], 
                $row['characterName'], 
                $row['userId'], 
                $row['level']
                ));
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题