How to make mysql generated posts to be independent onn their own - php

i am retrieving posts from a table called post . I wanted to add a commenting feature to this code, The problem is that the latest posts variables are dominant over others in that if you comment on an older post, the variables of the "latest post(which appears first because of the ORDER BY ID DECS criteria"
Someone help me make this posts independent on their own...Thanks
<?php
$sqlhash="SELECT * FROM posts ORDER BY id DESC ";
$result_hash = mysqli_query($conn,$sqlhash);
while($rowhash = mysqli_fetch_assoc( $result_hash))
{
$user = $rowhash['user'];
$message = $rowhash['post'];
$time = $rowhash['time'];
$id= $rowhash['id'];
$tt = date('m/d/Y H:i:s',$time);
$my_id = $_SESSION['user_id'];
$sql="SELECT * FROM users WHERE Full_name='$user' ";
$result_set = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc( $result_set))
{
$select_username = $row['Full_name'];
$profp = $row['pic'];
$my_id = $_SESSION['user_id'];
?>
<center><div class='post' style='width:48%; height:40%; align:middle; text-align:left; margin:30px 0'>
<img width="70" height="70" src='uploads/<?php echo $profp; ?>'><br><p style='color:#0c88b5'><b> <?php echo $id ;?><br><?php echo $user ;?>On:<?php echo $tt ; ?><h4><b><?php echo $message
;?></h4></p><hr>
<?php
$sqlcom="SELECT * FROM comment WHERE hash='$id' ";
$result_com = mysqli_query($conn,$sqlcom);
while($rowcom = mysqli_fetch_assoc( $result_com))
{
$usercom = $rowcom['comment'];
$comenter = $rowcom['user'];
echo "<p style='color:#0c88b5' $comenter</p>". ":" ;
echo $usercom. "<br>" ;
}
if (isset($_POST['commen'])) {
$sqlhash= "SELECT * FROM posts WHERE post= '$message' ";
$result_hash = mysqli_query($conn,$sqlhash);
while($rowhash = mysqli_fetch_assoc( $result_hash))
{
$user1 = $_SESSION['username'];
$comment = $_POST['commen'];
$time = $rowhash['time'];
$time2 = $_SESSION['time'];
$sql3 = "INSERT INTO comment (user, comment, hash) VALUES
('$user1','$comment', '$id')";
if($conn->query($sql3) === TRUE) {
header('Location: timeline.php');
}else {
echo"error";
}

Make some changes at database level in your post table to manage the reply thread on a post.
Add a parent_id column with default null that contains the post id for which the reply or comment is made.
For each comment or reply, put an entry in parent_id column.
To show post, fetch the records having parent_id IS NULL. By this you will get the post only, put order by on id to get in a proper order.
For each post you can retrieve comment or reply by putting a condition like parent_id IS NOT NULL
This will help you.

Related

Displaying link if no row exists in the database, otherwise display text

I have a table called flagged_posts in my database, and it has the following columns:
id
thought_id
flagged_by_id
What I am trying to do is that if the logged in user has already flagged the post, then don't allow them to flag the post again, and I am trying to achieve this by removing the anchor link and replacing it by a message.
Here is a snippet of my code:
<?php
$query = mysqli_query($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' AND shared ='yes' "."ORDER BY id DESC LIMIT {$start}, {$limit}");
while ($row = mysqli_fetch_array($query)) {
$thought_id = $row['id'];
$message_content = $row['message'];
$date_of_msg = $row['post_details'];
$thoughts_by = $row['added_by'];
$attachent = $row['attachment'];
$shared = $row['shared'];
// getting the id of the user who is logged in.
$see_if_flagged_q = mysqli_query($connect, "SELECT id FROM users WHERE username = '$username'");
$getting_deets = mysqli_fetch_assoc ($see_if_flagged_q);
$logged_in_user_id = $getting_deets ['id'];
echo "
<div class='more_options' style='float: right;'>";
$see_if_flagged_q2 = mysqli_query($connect, "SELECT * FROM flagged_posts WHERE flagged_by_id ='$logged_in_user_id' ");
while ($getting_deets2 = mysqli_fetch_assoc ($see_if_flagged_q2)){
$flagged_post_by_id = $getting_deets2 ['flagged_by_id'];
// If the user logged in has not flagged the post, i.e. there is no data in the database ..
// .. which says their user id has flagged this thought_id.. then display the link...
if ($logged_in_user_id == $flagged_post_by_id){
echo "<a href='/inc/flagged_post.php?id=$thought_id'> Flag </a>";
}
// if there is data stating this user has flagged this thought_id, then echo a message
if ($logged_in_user_id != $flagged_post_by_id) {
echo "Flagged";
}
}
echo " </div>";
}
?>
So assume I am logged in as Conor. Conor has an id of 8 (id obtained from users table). Conor flags a post with an id of 209 (thought_id obtained from user_thoughts table). So in my flagged posts table, I will see the following row:
id: 1
thought_id: 209
flagged_by_id: 8
At the moment, neither link nor the message is appearing. If I change my query, i.e. $see_if_flagged_q2 = mysqli_query($connect, "SELECT * FROM flagged_posts "); (removed the WHERE clause) then I get the message Flagged echo'd four times (because there are four rows in the flagged_posts table and they are echo's on every post, even those which have not been flagged by the logged in user.
Update:
Here is the updated code first of all:
$see_if_flagged_q2 = mysqli_query($connect, "SELECT * FROM flagged_posts WHERE flagged_by_id = '$logged_in_user_id'");
$test_num = mysqli_num_rows ($see_if_flagged_q2);
$getting_deets2 = mysqli_fetch_assoc ($see_if_flagged_q2);
$flagged_post_by_id = $getting_deets2['flagged_by_id'];
if ($flagged_post_by_id == $logged_in_user_id){
echo "<a href='/inc/flagged_post.php?id=$thought_id'> Flag </a>";
echo $test_num;
}
if ($flagged_post_by_id != $logged_in_user_id) {
echo "Flagged";
}
With the above, the link appears for all posts now, even if they are flagged. I have echo'd both $flagged_post_by_id and '$logged_in_user_id', which both echo the value of 12 (the id of Conor from users table). The values are correct and the number of rows returned by $test_num is also correct.
Ok, here's a reworking of your original code. I moved the data gathering part up front, so we have a setup section before we run the while loop on the thoughts. I changed a variable name here and there. Basically, we build a list of flagged entries, and then in the while loop the job is simpler. If the current row id is in the flagged_posts array, it's flagged, else present the link.
// get the id of the current user
$user_id_q = mysqli_query($connect, "SELECT id FROM users WHERE username = '$username'");
$getting_deets = mysqli_fetch_assoc($user_id_q);
$logged_in_user_id = $getting_deets['id'];
// build array of posts flagged by current user
$flagged_posts_q = mysqli_query($connect, "SELECT thought_id FROM flagged_posts WHERE flagged_by_id = '$logged_in_user_id'");
$flagged_posts = array();
while ($row = mysqli_fetch_array($flagged_posts_q)) {
$flagged_posts[] = $row['thought_id'];
}
$query = mysqli_query($connect, "SELECT * FROM user_thoughts WHERE added_by='$user' AND shared ='yes' "."ORDER BY id DESC LIMIT {$start}, {$limit}");
while ($row = mysqli_fetch_array($query)) {
//You could just use $row['foo'] down below, and skip all this
/*
$thought_id = $row['id'];
$message_content = $row['message'];
$date_of_msg = $row['post_details'];
$thoughts_by = $row['added_by'];
$attachent = $row['attachment'];
$shared = $row['shared'];
*/
echo "<div class='more_options' style='float: right;'>";
if (in_array($row['id'], $flagged_posts)){
echo "Flagged";
} else {
echo "<a href='/inc/flagged_post.php?id=".$row['id']."'> Flag </a>";
}
echo "</div>";
}

Displaying the username of the poster

I have looked far and wide through the lands of Stack Overflow, but have found no success in finding a solution to my extremely basic question.
I have a messaging system within my website and when a user posts a message, I would like their name to feature at the top of the article eg. "Posted by (name)".
At the moment, it displays the name of the logged in user, however this name changes depending on whoever is logged in at the time.
So, if I posted something under the name "Jim", and then logged in under the name "Bob", it would display the poster name as "Bob".
I am aware that my problem lies within $username = $_SESSION['username'];. I'm just not sure what to do about it.
<?php
require_once("nbbc/nbbc.php");
$bbcode = new BBCode;
$sql = "SELECT * FROM comment ORDER BY id DESC";
$res = mysqli_query($dbCon, $sql) or die(mysqli_error($dbCon));
$comment = "";
$username = $_SESSION['username'];
if(mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_assoc($res)) {
$id = $row['id'];
$date = $row['date'];
$content = $row['content'];
$bbcode->Parse($content);
$comment .= "
<div id='a_comment'>
<h1>Posted by $username on $date</h1>
<p>$content</p>
</div>
";
}
echo $comment;
} else {
echo "<div id='no_comments'>There are no comments to be displayed.</div>";
}
?>
Here's the rest of the code:
<?php
session_start();
include_once("inc/connection.php");
error_reporting(E_ALL); ini_set('display_errors', 1);
if(!isset($_SESSION['username'])) {
header("Location: login.php");
return;
}
if(isset($_POST['post'])) {
$content = strip_tags($_POST['content']);
$content = mysqli_real_escape_string($dbCon, $content);
date_default_timezone_set("Australia/Victoria");
$date = date('d-m-y h:i:sa');
$sql = "INSERT INTO comment (date, content) VALUES ('$date', '$content')";
mysqli_query($dbCon, $sql);
header("Location: members.php");
}
?>
Ideally you would store the user ID in the comment table, and then use the user table for a lookup when pulling the comment out. However, since I know nothing about your table structure, I'm going to give you instructions for storing the username in the comment table instead, and you can adjust for your needs.
Step 1: Alter your comment table to store the username
ALTER TABLE comment
ADD username VARCHAR(100) AFTER content;
Step 2: Store the username when storing the post
$sql = "INSERT INTO comment (date, content, username) VALUES ('$date', '$content', '{$_SESSION['username']}')";
Step 3: Assign the correct username when retrieving the data
$username = $row['username'];

deleting records from mysql table

Continuing with my simple CRUD, I'm stuck again...
So I have a table created called "usuaris" and a column called "id" which is my auto-increment and then another column called "usuari_nom". Now, I want to add "delete function", so when I am displaying the records of my table I've added a to delete it:
<div id="main">
<?php
global $conn;
$query = "SELECT * FROM usuaris";
if($grup_usuaris = mysqli_query($conn, $query)) {
echo "<table>";
echo "<tr><th>Usuaris</th><th>Accions</th></tr>";
while($row = mysqli_fetch_assoc($grup_usuaris)) {
echo "<tr><td>" . $row['usuari_nom'] . "</td><td>Eliminar usuari</td></tr>";
}
echo "</table>";
echo "+ Afegeix Usuari";
mysqli_free_result($grup_usuaris);
} else {
echo "query failed";
echo("Error description: " . mysqli_error($conn));
}
?>
</div>
So now, If I click on "eliminar usuari" it goes to the file where I am adding the query to delete, plus the id of that user; for example: "http://localhost/calendario/elimina_usuari.php?subject=6". But then, in the file elimina_usuari.php, how do I select the id to know what record to delete?
I've thought with $_GET but it doesn't seems to work, either with $_POST:
elimina_usuari.php
<?php
global $conn;
$usuari_id = $_GET['id'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
Any clue how can I get its id? Should I take it from the url somehow?
Thanks
you're doing fine.
just need to change this
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
as you're setting subject instead of id in your url
http://localhost/calendario/elimina_usuari.php?subject=6
^
and if you want to process id, like $_GET['id'], you need to change URL.
"http://localhost/calendario/elimina_usuari.php?id=6"
^ change here
EDIT
as per your comment,
you can use any $variable to $_POST or $_GET, it has nothing to do with the database column name.
Like you can use following.
"http://localhost/calendario/elimina_usuari.php?eve_mf=6"
and on elimina_usuari.php page,
$id = $_GET['eve_mf'];
and second part, why can I do that and I don't need to call it id as it is called in my db table?
Again, it's not the issue what you call variables in you local environment, all you to do(and should take care of) is to put right parameters in your sql query.
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
Here id is the name of your column name in your database. You can't change it here if you even want it to.
however, $usuari_id is your local variable, and you can change it whatever you want.
Hope I've explained what you're looking for :)
You can get the id with $_GET['subject'].
Please be aware about SQL injection as you are wrongly get the id of the user to be deleted:
$usuari_id = mysqli_real_escape_string($conn, $_GET['subject']);
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>
You just need to Get the exact variable name or parameter name which you have sent with your url
I mean see your url contains subject=6
that means you have to get subject instead of id;
please replace this code
$usuari_id = $_GET['id'];
to
$usuari_id = $_GET['subject'];
try this in elimina_usurai.php
<?php
global $conn;
$usuari_id = $_GET['subject'];
$query = "DELETE FROM subjects WHERE id = {$usuari_id} LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_affected_rows($conn) == 1) {
redirect_to("calendari.php");
} else {
echo "no eliminat";
}
?>

How do i make delete button work?

I am trying to make a delete button but it doesn't work.
$interogare = "SELECT * FROM comments JOIN users ON users.user_id = comments.user_id WHERE movie_id='$movie_id' ORDER BY date_posted DESC";
$result = mysqli_query($dbc, $interogare) or die(mysqli_error($dbc));
while($rand = mysqli_fetch_assoc($result))
{
echo 'Delete';
if(isset($_GET['com'])) {
$haidi = mysqli_real_escape_string($dbc,$_GET['com']);
$sql_del = "DELETE FROM comments WHERE comment_id = '$haidi'";
mysqli_query($dbc,$sql_del);
header('location: film.php?id='.$_GET['id'].'');
exit();
}
}
When i click the delete link it takes me to
film.php?com='.$rand['comment_id'].'
page but nothing happens,it should delete my comment and take me back to the page where the comment was.Can someone please help me figure this out ?
does this work?
<?php
$query = "
SELECT *
FROM comments
JOIN users ON users.user_id = comments.user_id
WHERE movie_id=" . $movie_id . "
ORDER BY date_posted DESC";
$result = mysqli_query($dbc, $query) or die(mysqli_error($dbc));
if (isset($_GET)) {
$getData = $_GET;
}
while ($rand = mysqli_fetch_assoc($result))
{
echo 'Delete';
if (isset($getData) && $getData['com']) {
$id = mysqli_real_escape_string($dbc, $getData['com']);
$query = "
DELETE FROM comments
WHERE comment_id=" . $id;
$result = mysqli_query($dbc, $query);
if($result)
{
header('location: film.php?id=' . $id . '');
}
exit();
}
}
i would rather grab the post once, and then make sure we are passing the same object around, so i set GET to a var. then, i didnt like the way the ids were being set in the query, because it wasnt as easy to see. then i got down to the way you were creating the header, and it looked like you were passing the id from some GET data, instead of the id you just extracted and set to a varibale, see above..., or was that your intention to use $_GET['id'] for that actually instead?
also, you might need to pass your data link in the mysqli_real_escape_string() method

What is The Scope Of PHP Variable for MYSQLI

I'm trying to set up a simple comment system and I want to create the correlation between the comment and the page landed.... so when a user arrives at blog.php?id=3 they would be presented the correct comments.
What I'm doing is creating the comments table with a pageid column. The pageid column will be filled when a user posts to the page. Maybe a hidden form field? How do I make this correlation within my MYSQLI
This is what I was thinking...
<?php
include_once("includes/check_login_status.php");
?>
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
include "includes/db_conx.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = "UPDATE content SET views=views+1 WHERE ID=$id";
$update = mysqli_query($db_conx,$sql);
$sql = "SELECT * FROM content WHERE id=$id LIMIT 1";
$result = mysqli_query($db_conx,$sql);
$productCount = mysqli_num_rows($result);
if ($productCount > 0) {
// get all the product details
while($row = mysqli_fetch_array($result)){
$article_title = $row["article_title"];
$category = $row["category"];
$readmore = $row["readmore"];
$author = $row["author"];
$date_added = $row["date_added"];
$article_content = $row["content"];
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
<?php
include_once "includes/db_conx.php";
$sql = "SELECT * FROM comment WHERE pageid ="$id"ORDER BY id DESC";
$sql_comments = mysqli_query($db_conx,$sql);
while($row = mysqli_fetch_array($sql_comments)){
$name = $row["name"];
$comment = $row["comment"];
$commentlist .= 'name : '.$name.'<br />comment : '.$comment.'<hr>';
}
//////////////
?>
Is the lower half in scope of the get variable? So that I can determine what page we're on? Can this type of variable be passed thorugh a variable in the comment form?
The 3rd sql statement contains an error:
$sql = "SELECT * FROM comment WHERE pageid ="$id"ORDER BY id DESC";
to
$sql = "SELECT * FROM comment WHERE pageid =".$id."ORDER BY id DESC";
You might also want to change the pre_replace statement to intval:
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
to
$id = intval($_GET['id']);
The reason being if $_GET['id'] = 'ABC123' then preg_replace will return 123 whereas the intval will return 0.

Categories