How to delete specific post with specific ID PHP [duplicate] - php

This question already has answers here:
How to add a delete button to a PHP form that will delete a row from a MySQL table
(5 answers)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 12 months ago.
I am creating a social site and users can upload replies to comment. They should also be able to delete those comments but I am having a problem doing that.
When I click the X button to delete the comment, I delete only the last comment uploaded. Or if I put the query inside of the while loop, I delete all of the comments. Can someone help me with this bug ?
$get_replies = $con->prepare("SELECT * FROM comment_replies WHERE comment_id = ? ");
$get_replies->bind_param("i", $comment_id);
$get_replies->execute();
$replies_result = $get_replies->get_result();
if ($replies_result->num_rows > 0) {
while ($row = $replies_result->fetch_assoc()) {
$reply_id = $row['reply_id'];
$reply_body = $row['reply_body'];
$reply_by = $row['reply_by'];
$comment_id = $row['comment_id'];
$date_added = $row['date_added'];
$deleted = $row['deleted'];
if ($deleted == 0) {
//Timeframe
$date_time_now = date("Y-m-d H:i:s");
$start_date = new DateTime($date_added); //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 . "y"; //1 year ago
}
else {
$time_message = $interval->y . "yrs"; //1+ year ago
}
}
else if ($interval-> m >= 1) {
if($interval->d == 0) {
$days = "";
}
else if($interval->d == 1) {
$days = $interval->d . "d";
}
else {
$days = $interval->d . "d";
}
if($interval->m == 1) {
$time_message = $interval->m . "mth";
}
else {
$time_message = $interval->m . "mth";
}
}
else if($interval->d >= 1) {
if($interval->d == 1) {
$time_message = $interval->d . "d";
//$time_message = "Yesterday";
}
else {
$time_message = $interval->d . "d";
}
}
else if($interval->h >= 1) {
if($interval->h == 1) {
$time_message = $interval->h . "h";
}
else {
$time_message = $interval->h . "h";
}
}
else if($interval->i >= 1) {
if($interval->i == 1) {
$time_message = $interval->i . "mins";
}
else {
$time_message = $interval->i . "mins";
}
}
else {
if($interval->s < 30) {
$time_message = "Just now";
}
else {
$time_message = $interval->s . "s";
}
}
?>
<div class="replies_parent">
<div class="reply_username"><?php echo "$reply_by"; ?></div>
<div class="reply_time"><p id="time_stamp"><?php echo "$time_message"; ?></p></div>
<div class="body_div"><p id="body_replies"><?php echo "$reply_body"; ?></p></div>
</div><br>
<?php
if ($userLoggedIn == $reply_by) {
?>
<form target="frame" method='POST'>
<!--<input type='hidden' name='reply_id' value='".htmlspecialchars($reply_id, ENT_QUOTES)."' />-->
<input name='comment_id' value=$comment_id style='display: none' />
<button onclick="afterDelete()" name="delete" class='delete_reply btn-danger' id="report-button" type="submit">X</button>
</form>
<?php
}
} else {
echo "";
}
}
if(isset($_POST['delete'])) {
$query = $con->prepare("UPDATE comment_replies SET deleted = 1 WHERE reply_id = ? AND reply_by = ?");
$query->bind_param("is", $reply_id, $userLoggedIn);
$query->execute();
}
}

Related

trouble in newsfeed using ajax, it shows everything like a loop

i'm actually working on a social media website using php and mysql,i have trouble in the creation of newsfeed using ajax,when i created the infinite scrolling newsfeed,everything works fine but the news feed never ends(i have only 12 posts in tabe) it shows everything repeatedly like a loop.
index_page.php
<div class="post_area"></div>
<img id="loading" src="assets/images/icons/loading.gif">
</div>
<script>
var userloggedin = '<?php echo $userloggedin; ?>';
$(document).ready(function(){
$('#loading').show();
//original ajax request for loading first posts
$.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userloggedin=" + userloggedin,
cache:false,
success: function(data){
$('#loading').hide();
$('.post_area').html(data);
}
});
$(window).scroll(function(){
var height = $('.post_area').height(); //div containing posts
var scroll_top = $(this).scrollTop();
var page = $('.post_area').find('.nextPage').val();
var noMorePosts = $('.post_area').find('.noMorePosts').val();
if((document.body.scrollHeight = document.body.scrollTop + window.innerHeight) && noMorePosts == 'false'){
$('#loading').show();
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userloggedin=" + userloggedin,
cache:false,
success: function(response){
$('.post_area').find('.nextPage').remove(); //removes current .nextpage
$('.post_area').find('.noMorePosts').remove(); //removes current .noMorePosts
$('#loading').hide();
$('.post_area').append(response);
}
});
}//end of if
return false;
});// end of $(window).scroll(function());
});
</script>
post.php(class)
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 items checked (not necessarily 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'];
//prepare user_to string so it can be included even if not posted to a specific user
if($row['user_to'] = "none"){
$user_to = "";
}
else{
$user_to_obj = new User($con, $row['user_to']);
$user_to_name =$user_to_obj->getFirstAndLastName();
$user_to = "<a href='" . $row['user_to'] . "'>" .$user_to_name . "</a>";
}
// check if a user who posted has their account closed
$added_by_obj = new User($this->con, $added_by);
if($added_by_obj->isClosed()){
continue;
}
if($num_iterations++ < $start)
continue;
//once 10 posts is loaded, break
if($count > $limit){
break;
}
else{
$count++;
}
$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'];
//Time Frame
$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"; // more than 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";
}
$str .= "<div class='status_post'>
<div class='post_profile_pic'>
<img src='$profile_pic' width='50'>
</div>
<div class='posted_by' style='color: #ACACAC;'>
<a href='$added_by' id='user_names_in_post'> $first_name $last_name </a> $user_to $time_message
</div>
<div id='post_body'>
$body
</div>
</div>
<hr>";
} // end of while
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'><p style='text-align: center;'> No more posts to show! </p>";
}
}// end of if
echo $str;
}//end of loadPostsFriends
ajax_load.php
<?php
include ("../../config/config.php");
include ("../classes/user.php");
include ("../classes/post.php");
$limit = 10; //numbr of posts to be loaded in one call;
$posts = new Post($con, $_REQUEST['userloggedin']);
$posts->loadPostsFriends($_REQUEST, $limit);
?>

How to display time_ago in another function

This function is to display what inside my table but i can't figure out how to dislay time_ago function where it should display seconds or hours or weeks just want to display seconds hour or week instead of month day and year but i get an error Call to undefined function time_ago() i don't know what i did wrong but i just can figure it out what went wrong with my code. got error on line 505 which is this ---> ' . time_ago($row['lastupdate']) . '
public static function getTicketByUserID(){
$mysqli = dbConnect();
$sql = "select
t.id as ticketid,
t.clientid,
t.comments,
t.assigneduser,
t.subject,
t.user,
t.lastupdate,
t.opendate,
(select c.department_name from department c where c.department_id = t.categoryid) as category,
(select ts.status
from ticketstatus ts
where ts.ticketid = t.id
and ts.statusdate = (select max(ts2.statusdate)
from ticketstatus ts2
where ts.ticketid = ts2.ticketid)) as status
from tickets t
where t.user = '". $_SESSION['name'] ."'
and (select ts.status
from ticketstatus ts
where ts.ticketid = t.id
and ts.statusdate = (select max(ts2.statusdate)
from ticketstatus ts2
where ts.ticketid = ts2.ticketid)) <> 'Closed'
order by t.opendate desc";
$result = $mysqli->query($sql);
echo '<table class="table table-hover table-striped table-responsive"><th>User</th><th>Subject</th><th>Group</th><th>Created</th><th>Last update</th><th>Status</th>';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row['status'] == 'Closed') { $class = "btn btn-danger";}
elseif ($row['status'] == 'Open') { $class = "btn btn-success";}
elseif ($row['status'] == 'Waiting on Client') {$class = "btn btn-info";}
else { $class = "btn btn-warning"; }
echo '<tr class="table_row">
<td>' .$row['user'] .'</td>
<td>' .$row['subject'] .'</td>
<td>' . $row['category'] . '</td>
<td>' . date("F j, Y, g:i a", strtotime($row['opendate'])) . '</td>
<td>' . time_ago($row['lastupdate']) . '</td>
<td><form method="POST">
<input name="ticketId" value="' . $row['ticketid'] . '" type="text" hidden />
<button type="submit" class="'.$class .'">'.$row['status'] .'</button></form>
</td>
</tr>';
}
} else {
echo '</table>';
$conn->close();
}
This is my function for time_ago get this error Call to undefined function time_ago() what did i do wrong?
function time_ago($ts)
{
$mins = floor((gmtime() - $ts)/60);
$hours = floor($mins/60);
$mins -= $hours*60;
$days = floor($hours/24);
$hours -= $days*24;
$weeks = floor($days/7);
$days -= $weeks*7;
if ($weeks == 1)
$w = "week";
elseif ($weeks > 1 && $weeks < 5)
$w = "weeks";
elseif ($weeks > 4)
$w = "weeks";
if ($weeks >= 1){
$we = "".$weeks." ".$w."";
}
if ($days == 1)
$d = "day";
elseif ($days > 1 && $days < 5)
$d = "day";
elseif ($days > 4)
$d = "days";
if ($days >= 1 ){
$da = "".$days." ".$d."";
}
if ($hours == 1)
$h = "hour";
elseif ($hours > 1 && $hours < 5)
$h = "hour";
elseif ($hours > 4)
$h = "hours";
if ($hours >= 1){
$ho = "".$hours." ".$h."";
}
if ($mins > 10 && $mins < 15)
$m = "minute";
elseif (($mins%10) == 1)
$m = "minute";
elseif (($mins%10) > 1 && ($mins%10) < 5)
$m = "minutes";
elseif (($mins%10) > 4)
$m = "minute";
if ($mins >= 1){
$mi = "".$mins." ".$m."";
}else{
$mi = "less than a minute";
}
if ($weeks || $days || $hours || $mins)
return $we." ".$da." ".$ho." ".$mi;
}

How to get birthday date in form of today, tomorrow, yesterday?

I want to get birthday dates in form of 'Today' ,'Tomorrow','Yesterday' form.
1.if candidate birthday was on 26-july-1991 it should be print 'yesterday'
2.if candidate birthday is on 27-july-1991 it should be print 'today'.
3.if candidate birthday will on 28-july-1991 it should be print 'tomorrow'.
code
$current = strtotime(date("Y-m-d"));
$date = strtotime("2014-07-24");
$datediff = $date - $current;
$difference = floor($datediff/(60*60*24*365));
if($difference==0)
{
echo 'today';
}
else if($difference > 1)
{
echo 'Future Date';
}
else if($difference > 0)
{
echo 'tomarrow';
}
else if($difference < -1)
{
echo 'Long Back';
}
else
{
echo 'yesterday';
}
Maybe a bit complicated solution, but here I compare month num and date num:
$current_month = date("n");
$current_day = date("j");
// date of birth
$dob = strtotime("1991-07-26");
$dob_month = date("n", $dob);
$dob_day = date("j", $dob);
if ($current_month == $dob_month) {
if ($current_day == $dob_day) {
echo 'TODAY';
} elseif ($current_day == $dob_day + 1) {
echo 'YESTERDAY';
} elseif($current_day == $dob_day - 1) {
echo 'TOMORROW';
} else {
echo 'IN this month';
}
} elseif ($current_month < $dob_month) {
echo 'In future';
} else {
echo 'Long back';
}
Use the php Date and Time class
Something like this:
$today=new DateTime("2017-07-27");
$other_day=new DateTime("2017-07-28");
$check = $today->diff($other_day);
$difference = (integer)$check->format( "%R%a" );
echo $difference;
just delete * 365 and your code should work

Ajax PHP - Result is only echoed if DOM Explorer is Open (Edge)

I have a page that calls a PHP script every 4 seconds with Ajax. The PHP script echoes out some text which is then put in a div on the page. (The PHP script does connect to a MySQL server, could that be the reason for my problems below?)
Here's the strange part. The first time the PHP script is called, it echoes all the text fine. However after 4 seconds, when Ajax calls the PHP script again, the page becomes blank. To make things even more strange, when I right-click View Source on MS Edge, all of the page content loads in, and then if I close the Source Code, after 4 seconds it disappears again.
Does anyone know why this is happening?
My JS file with Ajax:
function updateCandles(){
var candleIndexStart = $('#candle-index-start').text();
var candleSort = $('#candle-sort').text();
var resultArray = $.ajax({
type: 'GET',
url: 'php/display_candles.php',
data: {
'sort': candleSort,
'candle-start': candleIndexStart
},
async: false
}).responseText.split("h8ktncuidabciafvabc7932hcueqbc73gd8713gdy713gd6831df8136fd13d");
$('.candles').html(resultArray[0]);
$('#candle-counter').html(resultArray[1]);
setTimeout(updateCandles, 4000);
}
$(document).ready(function(){
updateCandles();
});
My PHP Script:
<?php
session_start();
function timeAgo($time_ago)
{
$time_ago = strtotime($time_ago);
$cur_time = time();
$time_elapsed = $cur_time - $time_ago;
$seconds = $time_elapsed ;
$minutes = round($time_elapsed / 60 );
$hours = round($time_elapsed / 3600);
$days = round($time_elapsed / 86400 );
$weeks = round($time_elapsed / 604800);
$months = round($time_elapsed / 2600640 );
$years = round($time_elapsed / 31207680 );
// Seconds
if($seconds <= 60){
return "just now";
}
//Minutes
else if($minutes <=60){
if($minutes==1){
return "one minute ago";
}
else{
return "$minutes minutes ago";
}
}
//Hours
else if($hours <=24){
if($hours==1){
return "an hour ago";
}else{
return "$hours hrs ago";
}
}
//Days
else if($days <= 7){
if($days==1){
return "yesterday";
}else{
return "$days days ago";
}
}
//Weeks
else if($weeks <= 4.3){
if($weeks==1){
return "a week ago";
}else{
return "$weeks weeks ago";
}
}
//Months
else if($months <=12){
if($months==1){
return "a month ago";
}else{
return "$months months ago";
}
}
//Years
else{
if($years==1){
return "one year ago";
}else{
return "$years years ago";
}
}
}
$connection = mysqli_connect("localhost", "username", "pass", "db");
if(!$connection) {
echo "Error";
}
if($_GET['teacher'] == 'yes'){
$result2 = mysqli_query($connection, "SELECT * FROM candles WHERE approved=0 ORDER BY date desc LIMIT " . $_GET['candle-start'] . ",20");
} else {
$result2 = mysqli_query($connection, "SELECT * FROM candles WHERE approved=1 ORDER BY date " . $_GET['sort'] . " LIMIT " . $_GET['candle-start'] . ",20");
}
if(mysqli_num_rows($result2) > 0) {
$counter = 0;
while($row = mysqli_fetch_assoc($result2)) {
$counter = $counter + 1;
if($counter % 2 == 1){
echo "</div>";
echo "<div class='candle-row'>";
}
if($row["approved"] == 1 and $_GET['teacher'] == 'yes') {
continue;
}
echo "<div class='candle'><div class='candle-icon'>";
echo '<span class="fa-stack fa-4x"><i class="fa fa-square-o fa-stack-2x"></i><i class="fa fa-' . $row["candle_icon_type"] . ' fa-stack-1x" style="color: ' . $row["colour"] . '"></i></span></div>';
echo '<div style="display:table;height:100%;"><div style="display:table-cell;vertical-align:middle;"><div>';
echo "<h3><a href='candle.php?id=" . $row["id"] . "'>For " . ucwords($row["title"]) . "</a></h3>";
echo "<br>";
$result3 = mysqli_query($connection, "SELECT * FROM users WHERE id=" . $row['user_id'] . " LIMIT 1");
if(mysqli_num_rows($result3) > 0) {
while($row1 = mysqli_fetch_assoc($result3)) {
if($row["anonymous"] == 1 and $_SESSION["user_group"] == '1'){
echo "<h4><a href='candle.php?id=" . $row["id"] . "'>Shared by an Anonymous User<br>";
} else {
echo "<h4><a href='candle.php?id=" . $row["id"] . "'>Shared by " . $row1["username"] . "<br>";
}
}
} else {
echo "<h4><a href='candle.php?id=" . $row["id"] . "'>Shared by Unknown<br>";
}
echo "Shared " . ucwords(timeAgo($row["date"])) . "<br>" . $row['fuel'] . " Fuel</a></h4></div></div></div>";
echo "</div>";
}
}
echo "h8ktncuidabciafvabc7932hcueqbc73gd8713gdy713gd6831df8136fd13d";
if($_GET['teacher']) {
$result1 = mysqli_query($connection, "SELECT id FROM candles WHERE approved=0");
} else {
$result1 = mysqli_query($connection, "SELECT id FROM candles WHERE approved=1");
}
if(mysqli_num_rows($result1) == 0){
echo '0 Candles';
} elseif(mysqli_num_rows($result1) == 1){
echo '1 Candle';
} else {
echo mysqli_num_rows($result1) . ' Candles';
}
mysqli_close($connection);
?>
yes, EDGE does seem to miss the console object when you don't have it opened (the DOM Explorer as you called it). when your console is closed, it doesn't "exist", so EDGE throws an error which you can't see because your console is closed.
(sounds weird to you? welcome to Microsoft created logic)!
I guess you are using the console.log() method in you code. so either you remove your console.log() calls or you put this workaround to the top of your javascript:
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };

convert timestamp to X second ago PHP

I'm currently developing an android app which retrieve data from SQL database using PHP. Every set of data got difference timestamp. The format of the timestamp in my database is (yyyy-mm-dd h:m:s). Now i want convert my timestamp so Android user will see the timestamp like (X second ago, X minutes ago or X days ago). I tried in my php code but result i get from the timestamp for every set of data is (1 days ago). every set of data show 1 days ago. Can anyone help me? thanks
Product.php
<?php
$response = array();
// include db connect class
require_once 'include/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM image_detail ORDER BY posted_at DESC") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["uid"] = $row["uid"];
$product["itemname"] = $row["itemname"];
$product["price"] = $row["price"];
$product["description"] = $row["description"];
$product["path"] = $row["path"];
$timestamp = $row["posted_at"];
$now = date("Y-m-d h:i:s");
$product["posted_at"] = xTimeAgo($timestamp, $now, "x");
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
function xTimeAgo ($oldTime, $newTime, $timeType) {
$timeCalc = strtotime($newTime) - strtotime($oldTime);
if ($timeType == "x") {
if ($timeCalc = 60) {
$timeType = "m";
}
if ($timeCalc = (60*60)) {
$timeType = "h";
}
if ($timeCalc = (60*60*24)) {
$timeType = "d";
}
}
if ($timeType == "s") {
$timeCalc .= " seconds ago";
}
if ($timeType == "m") {
$timeCalc = round($timeCalc/60) . " minutes ago";
}
if ($timeType == "h") {
$timeCalc = round($timeCalc/60/60) . " hours ago";
}
if ($timeType == "d") {
$timeCalc = round($timeCalc/60/60/24) . " days ago";
}
return $timeCalc;
}
?>
The code always returns one day because of this block of code:
if ($timeType == "x") {
if ($timeCalc = 60) {
$timeType = "m";
}
if ($timeCalc = (60*60)) {
$timeType = "h";
}
if ($timeCalc = (60*60*24)) {
$timeType = "d";
}
}
($timeCalc = 60) is not checking if $timeCalc is equal to 60, which is also wrong, it should check if it is greater than 60, it sets $timecalc to 60, which is also evaluated as true.
As a consequnce, every time you run the function, $timeCalc is first set to 60, then 60*60 and finally to 60*60*24. Likewise with $timeType, it is set to "m", then to "h" and finally to "d", and in this way, if you inspect your code, you see why it will always return one day.
Try setting the following if clauses instead:
if ($timeType == "x") {
if ($timeCalc > 60) {
$timeType = "m";
}
if ($timeCalc > (60*60)) {
$timeType = "h";
}
if ($timeCalc > (60*60*24)) {
$timeType = "d";
}
}
if ($timeType == "x") {
if ($timeCalc = 60) {
$timeType = "m";
}
if ($timeCalc = (60*60)) {
$timeType = "h";
}
if ($timeCalc = (60*60*24)) {
$timeType = "d";
}
}
You've got a proble here,
you affect $timeCalc in your if:
$timeCalc = 60
For exemple, i think you just forget == in all if.
Corrected code :
if ($timeType == "x") {
if ($timeCalc == 60) {
$timeType = "m";
}
if ($timeCalc == (60*60)) {
$timeType = "h";
}
if ($timeCalc == (60*60*24)) {
$timeType = "d";
}
}
The simplified script for same will be
function xTimeAgo ($oldTime, $newTime) {
$timeCalc = strtotime($newTime) – strtotime($oldTime);
if ($timeCalc > (60*60*24)) {$timeCalc = round($timeCalc/60/60/24) . ” days ago”;}
else if ($timeCalc > (60*60)) {$timeCalc = round($timeCalc/60/60) . ” hours ago”;}
else if ($timeCalc > 60) {$timeCalc = round($timeCalc/60) . ” minutes ago”;}
else if ($timeCalc > 0) {$timeCalc .= ” seconds ago”;}
return $timeCalc;
}
Try this. Hope this will help you.
There is a good example of code

Categories