我想在变量(likes
)中保存喜欢的数量($likes
)并将其打印在状态帖子($statuslist
)中,如果没有{foreach
则可能1}}循环因为我试过,我不能把$statuslist
放在循环中
但代码只能部分工作。它回应了喜欢的数量,但只有当每个状态帖子获得0,1,2,3等喜欢时。我不想要这个。我想在 EACH 帖子上回应其他人的喜欢数量
为此,foreach
循环和fetch_object
可以正常工作,但如果我使用foreach
循环,我必须将$statuslist
放在其中,我不希望这样。<登记/>
那么有什么解决方案吗?
MySQL的:
$statusQuery = $conn->query("
SELECT
status.id,
COUNT(status_likes.id) AS likes,
GROUP_CONCAT(users.username SEPARATOR '|') AS liked_by
FROM status
LEFT JOIN status_likes
ON status.id = status_likes.status
LEFT JOIN users
ON status_likes.user = users.id
GROUP BY status.id
");
$likes = "";
while($row = mysqli_fetch_array($statusQuery, MYSQLI_ASSOC)){
$likes = $row["likes"];
}
状态发布:
$statuslist .= '<div id="status_'.$statusid.'" class="status_boxes">';
$statuslist .= '<div>'.$statusDeleteButton.'<p id="status_date">';
$statuslist .= '<b>Post: </b>'.$postdate.'</p>'.$user_image.';
$statuslist .= '<p id="status_text">'.$data.'</p>';
$statuslist .= '.$shareButton.''.$likeButton.''.$likes.' people like it.
$statuslist .= '</div>'.$status_replies.'</div>';
修改:
我已经尝试过并且工作了,但我无法将喜欢的数量保存到可变数据中并在$statuslist
中回显它。
while($row = $statusQuery -> fetch_object()){
$statuses[] = $row;
}
foreach ($statuses as $status) {
echo $status->likes;
}
答案 0 :(得分:0)
require("MyPost.php"); // Needs to be at the top of the script!!
$statusQuery = $conn->query("
SELECT
status.id,
COUNT(status_likes.id) AS likes,
GROUP_CONCAT(users.username SEPARATOR '|') AS liked_by
FROM status
LEFT JOIN status_likes
ON status.id = status_likes.status
LEFT JOIN users
ON status_likes.user = users.id
GROUP BY status.id
");
$posts = array();
while($row = mysqli_fetch_array($statusQuery, MYSQLI_ASSOC)){
$mypost = new MyPost($row);
array_push($posts, $mypost);
}
foreach ($posts as $key => $post_value) {
// echo $post_value->id
echo $post_value->display_post();
}
通过 MyPost.php 创建一个新文件,并将其放在与脚本相同的文件夹中。 MyPost.php 的内容必须是以下代码。
class MyPost
{
// You can change these to private if you would like (change public to private)
public $statusDeleteButton = "DELETE_BUTTON_HERE";
public $likeButton = "LIKE_BUTTON_HERE";
public $shareButton = "LIKE_BUTTON_HERE";
// Keep public
public $id, $postdate, $user_image, $liked_by, $likes, $data, $status_replies;
// Code that is ran when a new MyPost object is created.
public function __construct($array)
{
// I am assuming you are getting these from the sql also?
//If you are then you can delete these variables.
$this->user_image = "";
$this->postdate = "";
$this->status_replies = "";
$this->data = "";
// Set the variables (Don't delete)
foreach ($array as $key => $value) {
$this->$key = $value;
}
}
// Return the string for the post.
public function display_post()
{
return '<div id="status_'.$this->id.'" class="status_boxes">
<div>'.$this->statusDeleteButton.'<p id="status_date">
<b>Post: </b>'.$this->postdate.'</p>'.$this->user_image.
'<p id="status_text">'.$this->data.'</p>'.
$this->shareButton.''.$this->likeButton.''.$this->likes.' people like it.
</div>'.$this->status_replies.'</div>';
}
}