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
Related
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();
}
}
I have a challenge I am trying to add all the time the user has spent online but I am getting wrong totals. I am taking values from mysql database and I want to get total hours, minutes and seconds for each user. Currently I am getting totals for each session but now I want total for all sessions and display all users in a table where I have username and time spent online and must be able to filter results by date getting total time spent in hours, minutes and seconds for the filtered date. How can I do that. My code is as follows:
$i=0;
foreach ($report as $online)
{
$id = $online['userid'];
$sql = "SELECT start_time, end_time FROM user_sessions where userid=$id AND end_time !='0000-00-00' || end_time != '' LIMIT $start, $per_page";
$timeOnline = $obj->MySQLSelect($sql);
++$i;
$start = $timeOnline[$i]['start_time'];
$end = $timeOnline[$i]['end_time'];
$totalhours = get_saved_time($end, $dstart);
$sum = $totalhours;
?>
<tr class="gradeA">
<?php if (!empty($sum)): ?>
<td><? echo $generalobjAdmin->clearName($online['fname'].' '.$online['lname']); ?></td>
<td align="center"><?= Convert($sum); ?></td>
<?php endif; ?>
</tr>
<? } ?>
public function get_saved_time($end_time,$start_time)
{
$past = $start_time;
$current = strtotime($end_time);
$past = strtotime($past);
return round(abs($current-$past));
}
function Convert($seconds) {
$hours = floor($seconds / 3600);
$mins = floor(($seconds / 60) % 60);
$secs = $seconds % 60;
if (strlen($hours) == 1)
$hours = "0" . $hours;
if (strlen($secs) == 1)
$seconds = "0" . $secs;
if (strlen($mins) == 1)
$minutes = "0" . $mins;
if ($hours == 0){
$mint="";
$secondss="";
if($mins > 01){
$mint = "$mins mins";
}else{
$mint = "$mins min";
}
if($secs > 01){
$secondss = "$secs seconds";
}else{
$secondss = "$secs second";
}
$ret = "$mint $secondss";
} else {
$mint="";
$secondss="";
if($mins > 01){
$mint = "$mins mins";
}else{
$mint = "$mins min";
}
if($secs > 01){
$secondss = "$secs seconds";
}else{
$secondss = "$secs second";
}
if($hours > 01){
$ret = "$hours hrs $mint $secondss";
}else{
$ret = "$hours hr $mint $secondss";
}
}
return $ret;
}
How to get the total number of monts, days, and minutes from a given minute. Say for example given a value in minutes 93366 should return 2 months ,5 days and 5 hours. This is what I've tried so far.
function convert_minutes($minutes, $output) {
if ($minutes >= 43833) {
$whole_month = 0;
$decimal_month = 0;
$label = "";
$months = $minutes / 43833;
list($whole_month, $decimal_month) = sscanf($months, '%d.%d');
if ($months > 1) {
$label = "months";
} else {
$label = "month";
}
$output .= $months . " " . $label;
$decimal_month = "0." . $decimal_month;
if ($decimal_month != 0) {
return $this->convert_minutes($decimal_month, $output);
} else {
return $output;
}
} elseif ($minutes >= 1440) {
$whole_day = 0;
$decimal_day = 0;
$label = "";
$days = $minutes / 1440;
list($whole_day, $decimal_day) = sscanf($days, '%d.%d');
if ($days > 1) {
$label = "days";
} else {
$label = "day";
}
$output .= $days . " " . $label;
$decimal_day = "0." . $decimal_day;
if ($decimal_day != 0) {
return $this->convert_minutes($decimal_day, $output);
} else {
return $output;
}
} elseif ($minutes >= 60) {
$whole_minutes = 0;
$decimal_minutes = 0;
$label = "";
$min = $minutes / 60;
list($whole_minutes, $decimal_minutes) = sscanf($min, '%d.%d');
if ($min > 1) {
$label = "minutes";
} else {
$label = "minute";
}
$output .= $min . " " . $label;
$decimal_minutes = "0." . $decimal_minutes;
if ($decimal_minutes != 0) {
return $output . " and " . $decimal_minutes . " minutes";
} else {
return $output;
}
}
}
EDIT
I just wanted to get the estimate. Assuming 1 hour is 60 minutes and 1 day is 1440 minutes and 1 month is 43,200. I am developing a document tracking system and would just like to calculate how long a document stayed in a particular office based on the date received and date released.
You can use floor and mod operator.
Floor rounds down a number.
The modulo operator will give you what is left if split evenly.
Example 5%2 = 1
Since 2*2 = 4 and the remaining is 1.
Echo floor(93366/43200) . " months\n";
$rem = 93366%43200;
Echo floor($rem/1440) . " days\n";
$rem = $rem%1440;
Echo floor($rem/60) . " hours\n";
Echo $rem%60 . " minutes";
Output:
2 months
4 days
20 hours
6 minutes
https://3v4l.org/RreDY
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 () { };
This code is used to take values inputted from a form but this does not take a year entered as 0100 as 0100 but as 1915, this is then used with the JS seen in one of my other questions any help here would be very good, I think the issue is something to do where the year is taken but I just can't get this to work correctly. Is this a limitation of php?
<?php
$year = "";
$month = "";
$day = "";
if (isset($_GET['year']) && !empty($_GET['year'])) {
$year = $_GET['year'];
}
if (isset($_GET['month']) && !empty($_GET['month'])) {
$month = $_GET['month'];
$monthNumber = date('m', strtotime("$month 1 Y"));
}
if (isset($_GET['day']) && !empty($_GET['day'])) {
$day = $_GET['day'];
}
if ($year != "" && $monthNumber != "" && $day != "") {
$fullUrlDate = $year . "-" . $monthNumber . "-" . $day;
$urlDate = new DateTime(date($fullUrlDate));
$today = new DateTime(date("Y-m-d H:i:s"));
$interval = $urlDate->diff($today);
$gapYears = $interval->y;
$gapMonths = $interval->m;
$gapDays = $interval->d;
$gapDaysTotal = $interval->days;
$gapWeeksTotal = round($interval->days/7);
$gapHours = $interval->h;
$gapMinutes = $interval->i;
$gapSeconds = $interval->s;
if ($gapWeeksTotal == 1) {
$gapWeeksSuffix = "";
} else {
$gapWeeksSuffix = "s";
}
if ($gapDays == 1) {
$gapDaysSuffix = "";
} else {
$gapDaysSuffix = "s";
}
$ordinalSuffix = date("S", strtotime($fullUrlDate));
if (strtotime($fullUrlDate) < strtotime(date("Y-m-d H:i:s")) ) {
$dateInThePast = true;
} else {
$dateInThePast = false;
}
// Months gap
$monthsInterval = date_diff($urlDate, $today);
$monthsGap = $monthsInterval->m + ($monthsInterval->y * 12);
$gapMonthsSuffix = ($monthsGap == 1 ? "" : "s");
DateTime has no such limitation, but the date function you use to initialise it, does. You can use DateTime::setDate to set any year you want:
php > $a = new DateTime("2015-08-24");
php > echo $a->format(DateTime::ISO8601);
2015-08-24T00:00:00+0000
php > $a->setDate(90, 8, 24);
php > echo $a->format(DateTime::ISO8601);
0090-08-24T00:00:00+0000
php > $a->setDate(90090, 8, 24);
php > echo $a->format(DateTime::ISO8601);
90090-08-24T00:00:00+0000