gpt4 book ai didi

php - 在 PHP 中使用 MYSQL 查找访问类

转载 作者:行者123 更新时间:2023-11-29 14:38:30 25 4
gpt4 key购买 nike

我正在用 PHP 制作一个简单的评论系统。对于我的每条评论,我都想查找发表该评论的用户并获取他们的详细信息。

我的类(class)如下:

class getuser {
public function __construct($userid) {
$userquery = "SELECT * FROM users WHERE id = ".$userid."";
$userresult = mysql_query($userquery);
while($user = mysql_fetch_array($userresult)){
$this->uid = $user['id'];
$this->username = $user['username'];
$this->avatar = $user['avatar'];
}
}
}
class getcomment {
public function __construct($postid) {
$commentquery = "SELECT * FROM comments WHERE postid = ".$postid."";
$commentresult = mysql_query($commentquery);
while($comment = mysql_fetch_array($commentresult)){
$this->uid = $comment['uid'];
$this->comment = $comment['comment'];
$this->timestamp = $comment['timestamp'];
$this->likes = $comment['likes'];
$this->reported = $comment['reported'];

//get user info for this comment
$this->getuser = new getuser($this->uid);
}
}
}

我在访问我的页面上的此信息时遇到问题...

                $comments = new getcomment($postid);

foreach($comments as $comment){

echo $comment->username."<br>";

}

数据库中有两条具有此帖子 ID 的评论。是 while 循环导致了这个问题吗?如何返回所有附有相关用户信息的评论?

提前非常感谢

最佳答案

while 循环没问题,不好的是 getcomment 的构造函数,
因为您在循环期间覆盖了每个 $this 属性。

此外,$comments 是一个对象,而不是数组。
可能的修复:-

构造函数:-

 $this->comments = array();
$idx = 0;
while($comment = mysql_fetch_object($commentresult))
{
$this->comments[$idx] = $comment;
$this->comments[$idx]->getuser = new getuser($comment->uid);
++$idx;
}

访问:-

$obj = new getcomment($postid);
foreach($obj->comments as $comment)
{
echo $comment->getuser->username."<br>";
}

关于php - 在 PHP 中使用 MYSQL 查找访问类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8486107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com