我是PHP新手并使用序列化数据
我有一个数据库,它有2个表,用户&字符。 characterId与userId有关系。
用户有2个字符,所以我想用以下代码获取数据:
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.";
}
}
}
如果我想显示数据,我使用以下代码:
//some code
$character = unserialize($_SESSION["character"]);
$output .= $character->getCharacterName() . "<br>";
//some code
我的问题是,当我var_dump($ _SESSION [“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”;}“
我的问题是,是否可以在序列化数据中包含多个“字符”?
答案 0 :(得分:0)
您没有循环结果。您只是将找到的第一个结果添加到会话中
你需要这样的东西来替换你if
阻止:
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']
));
}
}