[英]How to show/fetch amount of posts, comments etc a user has made
我想向用戶展示他們在個人資料部分創建的帖子、評論等的數量,就像存在的任何其他論壇一樣。 我正在使用 php 和 MYSQLI 執行此操作。 帖子表:
1 post_id Primary int(11) AUTO_INCREMENT
2 title varchar(255)
3 users_id int(11)
4 content varchar(500)
5 type int(11)
6 imagepath varchar(50)
7 date_created datetime
我試圖在 post 表中添加另一列,並在每次用戶通過 INSERT 語句在 php 中發布帖子時將其值增加 1,但它的值僅保持在 1,即使用戶繼續創建更多帖子。 這是我嘗試過的:
function createPost($conn, $content, $title, $users_id, $date_created, $type, $total_post){
$sql = "INSERT INTO post (title, users_id, content, date_created, type, total_post) VALUES (?,?,?,?,?,?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)){
header("location: ../home.php?error=stmtfailed");
exit();
}
$mysqltime = date ('Y-m-d H:i:s');
$total_post++;
$type;
mysqli_stmt_bind_param($stmt, "ssssss", $title, $users_id, $content, $mysqltime, $type, $total_post);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
header("location: ../home.php?error=noerroronpost");
exit();
}
這是在 profile.php 中,我試圖向用戶顯示信息
$id = $_SESSION["userid"];
$stmt = $conn->prepare('SELECT * from post LEFT JOIN users on users.users_id = ? order by post_id DESC;');
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
echo "<div class='userinfo'>";
echo "<h5 id='usernameprofile'>" ."Username: " .$row["users_username"] ."</h5>";
echo "<h5 id='usernameprofile'>" ."Registration date: " .$row["create_datetime"] ."</h5>";
echo "<h5 id='usernameprofile'>" ."Posts: " .$row["post_id"] ."</h5>"; echo "<br>";
echo "</div>";
}
$stmt->close();
編輯:感謝 ADyson,他提供的查詢非常有效。 我稍微調整了一下,只顯示帖子的數量。
$id = $_SESSION["userid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('SELECT COUNT(p.post_id) as total_posts from post p INNER JOIN users ON users.users_id = p.users_id WHERE p.users_id = ?;');
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
$count = $row['total_posts'];
echo "<div class='usertotalpost'>";
echo "<h5 id='totalposts'>" ."Posts: " .$count ."</h5>"; echo "<br>";
echo "</div>";
}
$stmt->close();
如果您想查看每個用戶的總數,您仍然需要計數和分組。 而且您的聯接樣式也完全錯誤-您應該將每個表中的列鏈接在一起以進行聯接,而不僅僅是限制輸入字段。
試試這樣:
SELECT
u.users_username,
u.create_datetime,
COUNT(p.post_id) AS total_posts
FROM
post p
INNER JOIN users
ON users.users_id = p.users_id
WHERE
p.users_id = ?
GROUP BY
u.users_username,
u.create_datetime
(顯然 WHERE 子句是可選的 - 如果您想查看所有用戶的總計列表,則將其刪除。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.