How to display time_ago in another function - php

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;
}

Related

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

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();
}
}

Speeding up PHP script

I'm working on a calendar for my office. Every people has his own column and there is a line for every day.
There are some periodic date, where, for example, given people have to be working on the week-end. But most of the dates are coming from a MySQL database.
So it does a double loop (people vs dates) in which every dates have to be check for the person, what kind of occupation he has on this day.
Is there a way to optimize this script, because online it take at least 2-3 seconds (only 0.03 seconds according to PHP, but I don't feel like it's correct) and more than 8 seconds (again according to PHP) on our network! And this is just for 5 months, we'd like to have it for the whole year.
You can find a test version here (just to see the HTML and CSS): http://mybees.ch/for/tableau.php
And here is the PHP in it:
//Creating the line for the collaborators
$ids;
$ma_count=0;
$ma_name_query = mysqli_query($bdi,"SELECT DISTINCT m.id, m.name, m.vorname, m.grup FROM ma m, ma_pos mp WHERE m.id = mp.maid AND m.grup != 14 ORDER BY m.grup, mp.posid, m.name, m.vorname");
while($ma_name = mysqli_fetch_assoc($ma_name_query)) {
echo '<div class="cell name">'.$ma_name['name'].' '.$ma_name['vorname'].'</div>';
$ids[$ma_count] = $ma_name['id'];
$grup[$ma_count] = $ma_name['grup'];
$ma_count++;
}
// Check if special group day
$firstGroup = 1;
$firstDate = strtotime("$year-01-01 00:00 GMT");
$picket = array();
if (date("N", $firstDate) == 2)// Tuesday
$firstDate -= 24 * 3600;
elseif (date("N", $firstDate) == 3)// Wednesday
$firstDate -= 2 * 24 * 3600;
elseif (date("N", $firstDate) == 5)// Friday
$firstDate -= 24 * 3600;
elseif (date("N", $firstDate) == 6)// Saturday
$firstDate -= 2 * 24 * 3600;
elseif (date("N", $firstDate) == 7)// Sunday
$firstDate -= 3 * 24 * 3600;
for ($date = $firstDate; $date <= strtotime("$year-12-31 00:00 GMT"); $date += 24 * 3600) {
$weekNb = date("W",$date);
$weekDay = date("N",$date); // Monday = 1, Sunday = 7
if ($weekDay < 4)
$group = $weekNb % 4 - 1 + $firstGroup;
else
$group = $weekNb % 4 - 2 + $firstGroup;
if ($group == 0)
$group = 4;
if ($group == -1)
$group = 3;
$picket[$date] = $group;
}
$groupColor = ["yellow", "blue", "red", "green"];
function isPicket($date, $grup) {
global $picket, $groupColor;
//global $picket, $groupColor;
if ($grup < 5) {
if ($picket[$date] == $grup)
return " style='background-color: ".$groupColor[$picket[$date]-1]."'";
}
}
$today_stp = time() - time() % (24 * 3600) - 11 * 24 * 3600;
$frei_query_text = "SELECT id_ma, date1, date2, free.id as type, moment, remark, location FROM frei, free WHERE free.id = frei.type AND date1 BETWEEN CAST('$date1' AS DATE) AND CAST('$date2' AS DATE)";
$frei_query = mysqli_query($bdi, $frei_query_text);
$free = array();
while($frei = mysqli_fetch_assoc($frei_query)) {
$free[] = $frei;
}
// Filling the lines
for ($date = strtotime($date1); $date <= strtotime($date2); $date += 24 * 3600) {
$today = ($date == $today_stp) ? ' id="today"':'';
echo "<div class='clear'$today>";
$class = (date('N', $date) < 6) ? 'week' : 'weekend';
echo "<div class='date $class line'>".date("D, d.m.", $date)."</div>";
for ($i = 0; $i < $ma_count; $i++) {
echo "<div class='cell line $class'".isPicket($date,$grup[$i]).">
<div class='small-cell".isColor($ids[$i], $date, 0)."' id='divUp-".$ids[$i]."-$date'> </div>
<div class='small-cell".isColor($ids[$i], $date, 1)."' id='divDown-".$ids[$i]."-$date'> </div>
</div>";
}
echo '</div>';
}
function isColor($id_ma, $date, $moment) {
global $free;
for ($i = 0; $i < count($free); $i++) {
if ($id_ma == $free[$i]['id_ma']) {
if ($date >= strtotime($free[$i]['date1']) && $date <= strtotime($free[$i]['date2'])) {
if ($free[$i]['moment'] == $moment || $free[$i]['moment'] == 2) {
$type = $free[$i]['type'];
$style = "";
if ($type > 1 && $type < 5)
$style = " urlaub";
if ($type > 4 && $type < 8)
$style = " frei";
if ($type > 7 && $type < 11)
$style = " ferien";
if (($type > 22 && $type < 34) || ($type > 37 && $type < 48))
$style = " kurse";
if ($type > 10 && $type < 17)
$style = " krank";
return " $style' title='".$free[$i]['remark'];
}
}
}
}
}
Thank you very much for your help

Echo date interval in a PHP calendar

I am creating a calendar and I am in a dire need of a solution. There are records of information in the database and the code reads these records. Two columns hold a date from and a date to. I have to output these dates that appear in the database in different colors. I have tried many times. And the problem is that the code outputs either the last record that it can fetch in the database or all the date periods however these periods get duplicated based on how many rows are there in the database.Here is the output I get
<div id="calender_section_top">
<ul>
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thu</li>
<li>Fri</li>
<li>Sat</li>
<li>Sun</li>
</ul>
</div>
<div id="calender_section_bot">
<ul>
<?php
$dateYear = ($year != '') ? $year : date("Y");
$dateMonth = ($month != '') ? $month : date("m");
$date = $dateYear . '-' . $dateMonth . '-01';
$currentMonthFirstDay = date("N", strtotime($date));
$totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN, $dateMonth, $dateYear);
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7) ? ($totalDaysOfMonth) : ($totalDaysOfMonth + $currentMonthFirstDay);
$boxDisplay = ($totalDaysOfMonthDisplay <= 35) ? 35 : 42;
$dayCount = 1;
for ($cb = 1; $cb <= $boxDisplay; $cb++) {
if (($cb >= $currentMonthFirstDay || $currentMonthFirstDay == 7) && $cb <= ($totalDaysOfMonthDisplay - 1)) {
$duh = array();
array_push($duh, $dayCount);
// Current date
$currentDate = $dateYear . '-' . $dateMonth . '-' . $dayCount;
$currentDate = strtotime($currentDate);
$eventNum = 0;
$sql = ("SELECT * FROM booking_2 GROUP BY date_from ORDER BY COUNT(book2_id) DESC");
$result = $this->connect()->query($sql);
$eventNum = $result->num_rows;
if ($eventNum > 0) {
while ($row = $result->fetch_assoc()) {
$date_from = $row['date_from'];
$date_to = $row['date_to'];
$time_from = strtotime($date_from);
$time_fromm = idate('d', $time_from);
$time_to = strtotime($date_to);
$time_too = idate('d', $time_to);
if ($currentDate >= $time_from && $currentDate <= $time_to) {
for ($i = $time_from; $i <= $time_to; $i++) {
$cope = array();
array_push($cope, $dayCount);
}
echo '<li id="' . $row['book2_id'] . '" style="background-color:#FF3232 !important;" date="' . date("Y-m-d H:i:s", $currentDate) . '" class="date_cell"><span>' . implode($cope) . '</span>';
}
}
if (!($currentDate >= $time_from && $currentDate <= $time_to)) {
for ($g = $time_from; $g <= $time_to; $g++) {
$duh = array();
array_push($duh, $dayCount);
}
echo '<li date="' . date("Y-m-d H:i:s", $currentDate) . '" class="date_cell"><span>' . implode($duh) . '</span>';
}
}
else {
echo '<li date="' . date("Y-m-d H:i:s", $currentDate) . '" class="date_cell"><span>' . implode($duh) . '</span>';
}
echo '</li>';
$dayCount++;
?>
<?php
}
else { ?>
<li><span> </span></li>
<?php
}
} ?>
</ul>
</div>
</div>
sorry for TL;DR. But really need help with this. I have tried all the ways I know so if you have a solution can you please be sure that this will work? I believe this is a hard problem to find a solution to.

PHP Calendar Issues

I have the following code that I created to generate a Calendar, but it has some issues:
//Labels
$dayLabels = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$monthLables = array("January","February","March","April","May","June","July","August","September","October","November","December");
//max values
$maxDays = 7;
$maxMonths = 12;
//stats
$forceMonth = $_GET['m'];
$forceYear = $_GET['y'];
$todayDate = date("d-m-Y");
$todayDate = date("d-m-Y", strtotime($todayDate));
$explodeToday = explode("-", $todayDate);
$currentDay = $explodeToday[0];
if(isset($forceMonth)) {
$currentMonth = $forceMonth;
} else {
$currentMonth = $explodeToday[1];
};
if(isset($forceYear)) {
$currentYear = $forceYear;
} else {
$currentYear = $explodeToday[2];
};
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $currentMonth, $currentYear);
//database values
$startDate = array("01-06-2015","25-06-2015");
$endDate = array("05-06-2015","05-07-2015");
$bookedUser = array("Dexter","James");
//counters
$daysIntoMonth = 0;
$dayCounter = 0;
//debug
echo '<p>Current Month: ' .$monthLables[$currentMonth-1]. ' / ' .$currentMonth. '</p>';
echo '<p>Current Year: ' .$currentYear. '</p>';
//start of Calendar
echo '<table>';
//print days of week
echo '<tr>';
foreach($dayLabels as $day) {
echo '<td style="border-bottom:dashed 1px #DDD;">' .$day. '</td>';
};
echo '</tr>';
while($daysIntoMonth < $daysInMonth) {
//days into month
$daysIntoMonth++;
$temp_inMonth = sprintf("%02d", $daysIntoMonth);
$daysIntoMonth = $temp_inMonth;
//days into week
$dayCounter++;
$temp_dayCounter = sprintf("%02d", $dayCounter);
$dayCounter = $temp_dayCounter;
//current calendar date
$calDate = date('d-m-Y', strtotime($daysIntoMonth. '-' .$currentMonth. '-' .$currentYear));
$timeCal = strtotime($calDate);
if($dayCounter == 1) {
echo '<tr>';
};
if($startKey = array_search($calDate, $startDate) !== FALSE) {
$booked = true;
};
if($endKey = array_search($calDate, $endDate) !== FALSE) {
$booked = false;
};
if($booked == true) {
echo '<td style="background-color:red;">' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
} else if($booked == true && array_search($calDate, $startDate) !== FALSE) {
echo '<td style="background-color:red;">' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
} else if($booked == false && array_search($calDate, $endDate) !== FALSE) {
echo '<td style="background-color:red;">' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
} else {
echo '<td>' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
}
if($dayCounter == $maxDays) {
echo '</tr>';
$dayCounter = 0;
};
};
//table is kill
echo '</table>';
The issues I have noticed:
Unable to put a $bookedUser for respective $startDate,$endDate.
When a booking laps over to another month, it skips all the dates until the $endDate.
All Months start on Monday, how would I go about making them start of correct days of the week.
Possible code examples to help me solve my issues would be great, thanks in advance.
Edit:
I have solved problem 3 by using the following code:
$firstDayofMonth = strtotime("01-$currentMonth-$currentYear");
$firstDayofMonth = date("D", $firstDayofMonth);
$firstDayofMonth = array_search($firstDayofMonth, $dayMiniLabels);
$firstDayofMonth = $firstDayofMonth + 1;
$startMonth = 0;
if($firstDayofMonth != 7) {
while($startMonth < $firstDayofMonth) {
echo '<td></td>';
$startMonth++;
$dayCounter++;
$temp_dayCounter = sprintf("%02d", $dayCounter);
$dayCounter = $temp_dayCounter;
};
};
For the days and months (problem 3), I would do this:
$todaysNumber = date('w');
$currentDayInText = $dayLabels[$todaysNumber];
And the same for the monhts.
Mostly, in my MySQL-tables, dates are placed like 2015-06-05 and not in European time notation. Maybe that could solve problem 1?

xx time ago function doesn't work

I am trying to display "{number} {unit-of-time} ago" in my chat. However, when I'm expecting something like "2 minutes ago", I see "45 years" instead.
Nobody has an answer?
Here is the script:
<?php
$con = mysql_connect("localhost", "user", "pword");
mysql_select_db('chat', $con);
$result1 = mysql_query("SELECT * FROM logs ORDER BY id ASC");
$tm = mysql_query("SELECT timestamp FROM logs ORDER BY id ASC");
function _ago($tm, $rcs = 0)
{
$cur_tm = time();
$dif = $cur_tm - $tm;
$pds = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
$lngh = array(1, 60, 3600, 86400, 604800, 2630880, 31570560);
for ($v = sizeof($lngh) - 1; ($v >= 0) && (($no = $dif / $lngh[$v]) <= 1); $v--) ;
if ($v < 0) $v = 0;
$_tm = $cur_tm - ($dif % $lngh[$v]);
$no = floor($no);
if ($no <> 1) $pds[$v] .= 's';
$x = sprintf("%d %s ", $no, $pds[$v]);
if (($rcs == 1) && ($v >= 1) && (($cur_tm - $_tm) > 0)) $x .= time_ago($_tm);
return $x;
}
$timeagochat = _ago($tm, $rcs = 0);
while ($extract = mysql_fetch_array($result1)) {
echo "<p class='show_message'><span class='uname'>" . $extract['username'] . "</span> <span class='time'>" . $timeagochat . " </span><br><span class='msg'>" . $extract['msg'] . "</span></p><br>";
}
?>
What can I do to let this function work?
You have to fetch the date:
$tm = mysql_query("SELECT timestamp AS t FROM logs ORDER by id ASC")->fetch_assoc()['t']; //obviously, check the size before you fetch
You probably want to use strtotime() so for instance:
$dif = $cur_tm-strtotime($tm);
The $dif will be in milliseconds.
What are you doing with the loops and the arrays? Too confusing.
5. WHY DO PEOPLE KEEP USING mysql_!!!

Categories