[英]Display data from two sql tables using PHP mySQL
我創建了這個社交網站http://friendquest.rf.gd 。 我在新聞提要中遇到問題,無法解決。 所以一切正常,但不是我想要的方式! 我制作了一個名為Posts and reposts的SQL表,其中posts是用戶輸入以顯示在我的網站中的新聞提要中的數據,並且repost的工作類似於Twitter上的“共享”按鈕或“ retweet”按鈕。
現在,我希望同時顯示兩個表。
例如,我發布了一個ID為31的帖子。現在,我的一個朋友轉發了ID 31,並按照應顯示的時間排序,如下所示:
將ID 3重新發布為ID 31
職位編號33
帖子ID 32
編號31
重新發布完成后,我的代碼如何顯示數據-
職位編號33
帖子ID 32
將ID 31重新發布為ID 31
編號31
我無法弄清楚如何根據發布的時間在頂部獲得轉發。這是我的轉發代碼
public function getRepostsPosts($post_id, $first_name, $last_name, $body, $imageDiv, $orig_poster, $imagePath){
$query = mysqli_query($this->con, "SELECT * FROM reposts WHERE post_id='$post_id'");
$html = "";
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_array($query)){
$repost_body = $row['body'];
$repost_by = $row['repost_by'];
$users_query = mysqli_query($this->con, "SELECT * FROM users WHERE username='$repost_by'");
$users_row = mysqli_fetch_array($users_query);
$reposted_first_name = $users_row['first_name'];
$reposted_last_name = $users_row['last_name'];
$num = mysqli_num_rows($query);
if($this->user_obj->isFriend($repost_by)){
$link = "<a href='$repost_by'> $reposted_first_name $reposted_last_name </a>";
}
else{
$link = "$reposted_first_name $reposted_last_name";
}
if($repost_body != ""){
$body_html = "<br>
<p>And said \"$repost_body\".</p>
<br>";
}
else{
$body_html = "";
}
$html .= "<div class='status_post'>
<div class='reposted_by' style='color:#ACACAC;'>
$link Reposted <a href='$orig_poster'>$first_name $last_name</a>'s <a href='post.php?id=$post_id'>Post</a>
$body_html
<div id='repost_body' onclick='location.href = \"post.php?id=$post_id\"'>
$body
<br>
$imageDiv
<br>
<br>
</div>
</div>
</div>
<div id='myModal$post_id' class='imageModal' style='display: none'>
<div class='modalContent'>
<img src='$imagePath' class='modalImage'>
<br>
<button class='button cursor' onclick='closeModal$post_id()'>Close</button>
</div>
</div>
<br>";
//return $html;
}
return $html;
}
else{
return "";
}
}
這是我的帖子代碼
public function loadPostsFriends($data, $limit) {
$page = $data['page'];
$userLoggedIn = $this->user_obj->getUsername();
if($page == 1)
$start = 0;
else
$start = ($page - 1) * $limit;
$str = ""; //String to return
$data_query = mysqli_query($this->con, "SELECT * FROM posts WHERE deleted='no' ORDER BY id DESC");
if(mysqli_num_rows($data_query) > 0) {
$num_iterations = 0; //Number of results checked (not necasserily posted)
$count = 1;
while($row = mysqli_fetch_array($data_query)) {
$id = $row['id'];
$body = $row['body'];
$added_by = $row['added_by'];
$date_time = $row['date_added'];
$imagePath = $row['image'];
//Prepare user_to string so it can be included even if not posted to a user
if($row['user_to'] == "none") {
$user_to = "";
}
else {
$user_to_obj = new User($this->con, $row['user_to']);
$user_to_name = $user_to_obj->getFirstAndLastName();
$user_to = "to <a href='" . $row['user_to'] ."'>" . $user_to_name . "</a>";
}
//Check if user who posted, has their account closed
$added_by_obj = new User($this->con, $added_by);
if($added_by_obj->isClosed()) {
continue;
}
$user_logged_obj = new User($this->con, $userLoggedIn);
if($user_logged_obj->isFriend($added_by)){
if($num_iterations++ < $start)
continue;
//Once 10 posts have been loaded, break
if($count > $limit) {
break;
}
else {
$count++;
}
if($userLoggedIn == $added_by){
$delete_button = "<button class='delete_button' id='post$id' data-toggle='modal' data-target='#delete_form$id'>Delete Post</button>";
$edit_button = "<button class='edit_button' id='post$id' data-toggle='modal' data-target='#edit_form$id'>Edit Post</button>";
$repost_button = "";
}
else{
$delete_button = "";
$edit_button = "";
$repost_button = "<button class='edit_button' id='post$id' data-toggle='modal' data-target='#repost_form$id'><img src='assets/images/icons/repost.png' class='repostButton'>Repost</button>";
}
$user_details_query = mysqli_query($this->con, "SELECT first_name, last_name, profile_pic FROM users WHERE username='$added_by'");
$user_row = mysqli_fetch_array($user_details_query);
$first_name = $user_row['first_name'];
$last_name = $user_row['last_name'];
$profile_pic = $user_row['profile_pic'];
?>
<script>
function openModal<?php echo $id?>(){
document.getElementById('myModal<?php echo $id ?>').style.display = "block";
}
function closeModal<?php echo $id?>(){
document.getElementById('myModal<?php echo $id ?>').style.display = "none";
}
function toggle<?php echo $id; ?>(){
var target = $(event.target);
if(!target.is("a") && !target.is("button") && !target.is("img") && !target.is("textarea") && !target.is("")){
var element = document.getElementById("toggleComment<?php echo $id; ?>");
if(element.style.display == "block"){
element.style.display = "none";
}
else{
element.style.display = "block";
}
}
}
</script>
<?php
$comments_check = mysqli_query($this->con, "SELECT * FROM comments WHERE post_id='$id'");
$comments_check_num = mysqli_num_rows($comments_check);
//Timeframe
$date_time_now = date("Y-m-d H:i:s");
$start_date = new DateTime($date_time); //Time of post
$end_date = new DateTime($date_time_now); //Current time
$interval = $start_date->diff($end_date); //Difference between dates
if($interval->y >= 1) {
if($interval == 1)
$time_message = $interval->y . " year ago"; //1 year ago
else
$time_message = $interval->y . " years ago"; //1+ year ago
}
else if ($interval-> m >= 1) {
if($interval->d == 0) {
$days = " ago";
}
else if($interval->d == 1) {
$days = $interval->d . " day ago";
}
else {
$days = $interval->d . " days ago";
}
if($interval->m == 1) {
$time_message = $interval->m . " month". $days;
}
else {
$time_message = $interval->m . " months". $days;
}
}
else if($interval->d >= 1) {
if($interval->d == 1) {
$time_message = "Yesterday";
}
else {
$time_message = $interval->d . " days ago";
}
}
else if($interval->h >= 1) {
if($interval->h == 1) {
$time_message = $interval->h . " hour ago";
}
else {
$time_message = $interval->h . " hours ago";
}
}
else if($interval->i >= 1) {
if($interval->i == 1) {
$time_message = $interval->i . " minute ago";
}
else {
$time_message = $interval->i . " minutes ago";
}
}
else {
if($interval->s < 30) {
$time_message = "Just now";
}
else {
$time_message = $interval->s . " seconds ago";
}
}
if($imagePath != "") {
$imageDiv = "<div class='postedImage'>
<img src='$imagePath' onclick='openModal$id()'>
</div>";
}
else {
$imageDiv = "";
}
if($this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath) != ""){
$str .= $this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath);
}
$str .= "<div class='status_post' onClick='javascript:toggle$id()'>
<div class='post_profile_pic'>
<img src='$profile_pic' width='50'>
</div>
<div class='posted_by' style='color:#ACACAC;'>
<a href='$added_by'> $first_name $last_name </a> $user_to $time_message
</div>
<div id='post_body'>
$body
<br>
$imageDiv
<br>
<br>
</div>
<div class='modal fade' id='edit_form$id' tabindex='-1' role='dialog' aria-labelledby='postModalLabel' aria-hidden='true'>
<div class='modal-dialog' role='document'>
<div class='modal-content'>
<div class='modal-header'>
<h5 class='modal-title' id='exampleModalLabel'>Edit Your Post</h5>
<button type='button' class='close' data-dismiss='modal' aria-label='Close'>
<span aria-hidden='true'>×</span>
</button>
</div>
<div class='modal-body'>
<p>Edit your Post</p>
<form class='post_form' action='index.php' method='POST'>
<div class='form-group'>
<textarea class='form-control' id='post_text' name='post_text' placeholder='Got something to edit?'>$body</textarea>
<input type='hidden' name='post_id' value='$id'>
<button type='submit' class='btn btn-primary' name='edit' id='post_button'>Post</button>
</div>
</form>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-secondary' data-dismiss='modal'>Close</button>
</div>
</div>
</div>
</div>
<div class='modal fade' id='delete_form$id' tabindex='-1' role='dialog' aria-labelledby='postModalLabel' aria-hidden='true'>
<div class='modal-dialog' role='document'>
<div class='modal-content'>
<div class='modal-header'>
<h5 class='modal-title' id='exampleModalLabel'>Delete Your Post</h5>
<button type='button' class='close' data-dismiss='modal' aria-label='Close'>
<span aria-hidden='true'>×</span>
</button>
</div>
<div class='modal-body'>
<p>Are you sure you want to Delete?</p>
<form class='post_form' action='index.php' method='POST'>
<div class='form-group'>
<input type='hidden' name='post_id' value='$id'>
<button type='submit' class='btn btn-primary' name='delete' id='post_button'>Yes!</button>
</div>
</form>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-secondary' data-dismiss='modal'>No!</button>
</div>
</div>
</div>
</div>
<div class='modal fade' id='repost_form$id' tabindex='-1' role='dialog' aria-labelledby='postModalLabel' aria-hidden='true'>
<div class='modal-dialog' role='document'>
<div class='modal-content'>
<div class='modal-header'>
<h5 class='modal-title' id='exampleModalLabel'>Repost the Post</h5>
<button type='button' class='close' data-dismiss='modal' aria-label='Close'>
<span aria-hidden='true'>×</span>
</button>
</div>
<div class='modal-body'>
<p>Repost</p>
<p>\"$body\"</p>
<form class='post_form' action='index.php' method='POST'>
<div class='form-group'>
<textarea class='form-control' id='post_text' name='post_text' placeholder='Want something to say about the Repost?'></textarea>
<input type='hidden' name='post_id' value='$id'>
<input type='hidden' name='repost_by' value='$userLoggedIn'>
<button type='submit' class='btn btn-primary' name='repost' id='post_button'>Repost!</button>
</div>
</form>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-secondary' data-dismiss='modal'>Cancel</button>
</div>
</div>
</div>
</div>
<div class='newsFeedPostOptions'>
Comments($comments_check_num)
<iframe src='like.php?post_id=$id' id='likes_iframe' scrolling='no'></iframe>
$delete_button
$edit_button
$repost_button
</div>
</div>
<div class='post_comment' id='toggleComment$id' style='display:none;'>
<iframe src='comment_frame.php?post_id=$id' id='comment_iframe' frameborder='0'>
</iframe>
</div>
<div id='myModal$id' class='imageModal' style='display: none'>
<div class='modalContent'>
<img src='$imagePath' class='modalImage'>
<br>
<button class='button cursor' onclick='closeModal$id()'>Close</button>
</div>
</div>
<br>";
}
} //End while loop
if($count > $limit)
$str .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'>
<input type='hidden' class='noMorePosts' value='false'>";
else
$str .= "<input type='hidden' class='noMorePosts' value='true'><center><p style='text-align: centre; padding-top: 30px; color: #ACACAC '> No more posts to show! </p></center>";
}
echo $str;
}
首先,我應該警告您有關SQL注入的風險,並且您的代碼可能會受到風險的影響,具體取決於您如何過濾$ post_id之類的內容,因為這可能會導致某人潛入drop table或類似的事情中而導致您的工作日趨嚴重。
我強烈建議您查看准備好的語句來避免這種情況,但更建議您查看高度維護的庫,這些庫將SQL構建工作抽象為查詢的更多程序化構建。 例如Eloquent,它是一個出色的MVC框架Laravel的一部分,但可以獨立使用,也可以作為其他框架的一部分使用。
要指出的另一件事是對數據庫的查詢過多,因為您有一個初始查詢來獲取轉發/發布,然后遍歷結果並在每個帖子中查詢用戶,因此您在數據庫中添加了太多查詢一個查詢可以達到相同結果的函數。 如果您是用代碼手動編寫SQL或切換到Eloquent,則可以使用聯接,這是一種很好的方式來執行“熱切加載”,即查詢一個表並使用要求它包括用戶或用戶的關系。其他與結構相關的事物,例如外鍵。 所有這些只花費您一個或兩個查詢,而不是多達n個查詢,其中n是重新發布/發布的次數。
if($this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath) != ""){
$str .= $this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath);
}
這有兩次執行相同的許多查詢的風險,第一種是只檢查是否存在重新發布,然后再次執行相同的功能請求。 考慮將第一次調用的結果分配給變量,並檢查條件,然后使用該變量(如果為true),請參見下文。
if (!empty($reposts = $this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath))) {
$str .= $reposts;
}
您甚至可以只使用三元數:
$str .= (
!empty($reposts = $this->getRepostsPosts($id, $first_name, $last_name, $body, $imageDiv, $added_by, $imagePath))
? $reposts
: ''
);
現在有很多東西要學習,但是確保您的SQL安全是一個很好的起點,隨着您發現新技術,代碼的效率將會提高。
至於您的問題,您顯示帖子的順序可能會受到程序設計方法的困擾,您真正應該做的是將一系列帖子和帖子重新構建為屬性對象,然后完成操作所有查詢以填充數組,您可以使用usort根據其項屬性之一(可能是日期時間屬性或您希望對其排序的其他值)對數組重新排序,然后在排序后可以使用foreach並一步一步構建HTML輸出。
這將需要大量的精力來提供此提議的更改的代碼的變更版本,因此,我認為您需要調整方法,並更多地考慮逐步執行代碼,並嘗試不開始准備數據表示在您仍在獲取數據而取回所有數據的同時,整理並縮小數據,然后進行演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.