PHP querying MySQL, showing "count(*)" - php

I have inherited an old system at work, php 4.4 and MySQL that we run our helpdesk software from, I cannot upgrade anything until next year.
I'm struggling with something though.
I need to show the total number of calls logged between 2 and 1 hour ago. in the database, the unix timestamp for each call logged is in the column "logdatex"
in my php I have the following
$OneHourAgo = strtotime('-1 hour'); //time 1 hour ago as Unix Timestamp
$TwoHoursAgo = strtotime('-400 hour'); // time 2 hours ago
$Test = mysql_query("select count(*) from opencall where logdatex between $OneHourAgo and $TwoHoursAgo") or die(mysql_error());
Now, in MySQL Query Browser, if I put in the query but replace the variables with the actual numbers (I did an echo to get the numbers) it works fine and returns the desired number:
select count(*) from opencall where logdatex between 1326767703 and
1386764103
(the above doesn't use a 1 hour sample, more like a few years) Please can you help me get the number in to a variable, I cannot figure out how to do this.
Any help appreciated

The mysql_query does not directly return the results of the query. Rather it returns a result resource. http://www.php.net/manual/en/function.mysql-query.php
So you will need to use mysql_fetch_row to get the results.
http://www.php.net/manual/en/function.mysql-fetch-row.php
$row = mysql_fetch_row($Test);
$count = $row[0];
If you have more than one row, you would loop until the mysql_fetch_row returns false. But since you know you are only going to get one row, you can do this.

You should change your query:
select count(*) from opencall where logdatex between $TwoHoursAgo and $OneHourAgo
Because http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between says, it should be between min and max.

I'm not sure to understand you but, may be that?
$OneHourAgo = strtotime('-1 hour'); //time 1 hour ago as Unix Timestamp
$TwoHoursAgo = strtotime('-2 hour'); // time 2 hours ago
A link: http://php.net/manual/es/function.strtotime.php

Related

PHP Delete MySQL Records Older Than 3 Days

I have the following at the top of every page so when the website is loaded by anyone PHP deletes any record in a specific database table that is older than 3 days.
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < DATE_SUB(DATE('m-d-Y'), INTERVAL 3 DAY");
The problem is nothing is being deleted.
The data type for my date column is varchar(20) and when I insert a date into MySQL it is entered using date("m-d-Y"). The name of my date field is date. So it appears that the above query would be correct, but I have done something wrong, and I am not certain as to what since every example I've looked at has basically looked the same except they used now() instead of date() but I use a specific date format so I can't use now() in my query.
What have I done wrong?
I even tried putting it into a function:
function deleteOversizeRows() {
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < DATE_SUB(DATE('m-d-Y'), INTERVAL 3 DAY");
}
deleteOversizeRows();
Try to provide date by calculating first and then use it in query like below
$date = date("m-d-Y", strtotime('-3 day'));
$conn = getConnected("oversizeBoard");
mysqli_query($conn, "DELETE FROM postedLoads WHERE date < '".$date."');
It might help you. If need any other solution or help, do ask here.
Use MySQL function TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2);
Function calculates difference between two dates and returns output based on the unit parameter passed .
Try this:
DELETE FROM postedLoads WHERE TIMESTAMPDIFF('DAY',date,now())<3;
For detailed info of function:http://www.w3resource.com/mysql/date-and-time-functions/mysql-timestampdiff-function.php

PHP Date to String to compare dates

I only have basic PHP knowledge and I'm using PHP+Mysql and trying to check the difference in days between 2 dates; the 1st date is formatted by myself in the script as a string:
$f_entrega=$_POST['year1']."-".$_POST['month1']."-".$_POST['day1'];
The second date ($f_dock) which is the one causing the issue is taken from the mysql database which column is in DATE format. To compare the dates I do the following:
if(!empty($_POST["id"])){
$f_entrega=$_POST['f_entrega_a']."-".$_POST['f_entrega_m']."-".$_POST['f_entrega_d'];
$f_entr=$f_entrega;
$mysqli=conectar();
$resultado = $mysqli->query("SELECT id,f_dock FROM pt");
$row = $resultado->fetch_assoc();
for ($i=0;$i<count($ids);$i++){
do{
if ($ids[$i]==$row["id"]){
$f_dock=$row["f_dock"];
break;
}
} while ($row = $resultado->fetch_assoc());
$error=0;
var_dump($f_dock);
$f_dock=strtotime($f_dock);
$f_dock=date('Ymd',$f_dock);
$f_entrega=$f_entr;
$f_entrega=strtotime($f_entrega);
$f_entrega=date('Ymd',$f_entrega);
$f_dock=DateTime::createFromFormat('Ymd',$f_dock);
$f_entrega=DateTime::createFromFormat('Ymd',$f_entrega);
$dias_vendor=date_diff($f_dock,$f_entrega);
$tat=$dias_vendor->format('%R%a');
Sometimes it works correctly, but other times I get Warning: strtotime() expects parameter 1 to be string, object given in [first line] and $tat is not correctly calculated and has strange values.
I've tried different solutions like $f_dock=(string)$f_dock before but finally the convertion always fails in some cases. Thanks in advance for any tip.
The error that you are getting is because the string you are entering is not a valid string for the strtotime() function to convert.
For instance 2015-08-31 will convert just fine, as will today, tomorrow or +7 days.
For more specific help you will need to tell us what the value of $f_dock is (as Marcos says in his comment, var_dump($f_dock) will get you this).
However, on to the solution:
$date1 = strtotime($f_dock); //timestamp in seconds
$date2 = strtotime($f_entrega); //same for the second date
$difference = $date1 - $date2; //difference in seconds between the dates
$days = floor($difference/86400);
86400 is the number of seconds in a day, so find out how many seconds difference there is, then see how many days worth of seconds are in there and use floor() to round the number down. Job done.

Retrieve rows within current month, week, and day using php and mysql

I have a mysql table events with column event_date varchar(10) which takes in dates in the form 7-5-2014.
I have an object which can give me:
// displays current month (5)
$m = $time->getMonth();
echo $m;
//displays current day (1)
$d = $time->getDay();
echo $d;
// displays current year (2014)
$y = $time->getYear();
echo $y;
I am trying to figure out a way to get events within the current day, month, and year.
The php query below is wrong but it gives you and idea as to what im trying to do:
$eventsWithinDay = query("SELECT * FROM events WHERE LEFT(event_date, 2)='%s'", $d);
How can I do this correctly?
Better yet, what is the most efficient way to do this?
I can make any necessary changes to the database or php.
Thanks in advance.
You an do it in various ways. For instance:
SELECT smth FROM somewhere WHERE datefield LIKE '2014-05-%'
OR
SELECT smth FROM somewhere WHERE datefield >= $start_interval and date <= $end_interval
In the latter case you'd have your date stored in a BIGINT column and use php's time() to set its value. Then using PHP's time functions (like strtotime('-1 day')) get timestamps for dates you wish to query against. So a simple example would be:
$q = "SELECT ... WHERE datefield >= " . strtotime('-2 days') // this would search for dates from at least 2 days ago
You could also use MYSQL's built-in date-time functions, but i have no experience with those so i'm not going to advice on something i don't know myself :)

Why isnt my MySQL BETWEEN operator not working?

MySQL table "flightSched" is connected to time, similar to the one below:
flightNo |day |time |arrivalTimeSec
=============================================
WERE112 |Tuesday | 1:00 |1381186800
FGHG234 |Tuesday |23:00 |1381266000
CGHF345 |Tuesday |00:00 |1381183200
I have a mysql query that select all data between two times. This is the query:
$CurrentTimeMinus30min = date('H:i', strtotime('-30 minutes')); //Current Time minus 30minutes
$CurrentTimeMinus30min = strtotime($CurrentTimeMinus30min);
$CurrentTimePlus4Hours = date('H:i', strtotime('+240 minutes')); //Current Time plus 4 hours
$CurrentTimePlus4Hours = strtotime($CurrentTimePlus4Hours);
$query = $mysqli->query("
SELECT * FROM flightSched
WHERE day = '$currentDay'
AND arrivalTimeSec
BETWEEN '$CurrentTimeMinus30min'
AND '$CurrentTimePlus4Hours'
");
I was advised to used strtotime() function on the time values to be able to use them in a BETWEEN MySQL query. This doesn't seem to be working at all.
Where am I going wrong with this query? Any help will be appreciated.
today I found the same problem with yours (mine about coordinates).
and I found out that in some case, a BETWEEN operator can only be used like this
..... WHERE columname BETWEEN smallervalue AND biggervalue
previously I've tried with the biggervalue at front since I dealt with negative numbers, and it fails.
you might found the same problem with your timestamp.
strtotime returns a timestamp so passing that into the MySQL query, like above, won't work. Try using FROM_UNIXTIME instead.
$query = $mysqli->query("SELECT * FROM flightSched
WHERE day = '$currentDay'
AND FROM_UNIXTIME(arrivalTimeSec) BETWEEN FROM_UNIXTIME($CurrentTimeMinus30min) AND FROM_UNIXTIME($CurrentTimePlus4Hours) " );
EDIT - I hadn't noticed that arrivalTimeSec was also a timestamp. The above mightn't be a workable answer for you, but try it. If it doesn't work, as others say, define what you mean by
This doesn't seem to be working at all.
Is it not returning any rows? Is it returning an error? Can you print out $CurrentTimeMinus30min and $CurrentTimePlus4Hours? Narrow down the potential areas for problems.
Have you tried to encapsulate the between? This could potentially solve your problem:
SELECT * FROM flightSched
WHERE day = '$currentDay'
AND (arrivalTimeSec BETWEEN '$CurrentTimeMinus30min' AND '$CurrentTimePlus4Hours')
Also why not just do:
$CurrentTimeMinus30min = strtotime('-30 minutes');
Or
$CurrentTimeMinus30min = strtotime(date('Y-m-d H:i:00', strtotime('-30 minutes')));
Please send us some examples of what your variables are generating.
Your time calculation with date("H:i",...) and strtotime(..) seems to actually produce the correct results, although there is a much easier way to add/substract n minutes from the current time:
$now = time();
$currentTimeMinus30min = $now - 30*60; // 30 minutes * 60 seconds
$currentTimePlus4Hours = $now + 4*60*60; // 4 hours * 60 minutes * 60 seconds
(I assume your time entries in your database are unix timestamps.)
Your query looks fine, too, but there are a few things to keep in mind:
You have redundant fields in your database (day and time can be calculated from the timestamp)
Working with time variables can easily lead to confusion, as the time passes on and if you have no entries in your database that match the specified time range (-30m to +240m) the result set is empty. So to test the query update the database with current time stamps.
I would suggest the following:
Drop the redundant columns day and time and just use the timestamp as base for your calculations, because the day and time is already included in the timestamp. So just use a simple query like
select * from flightShed
where arrivalTime between $begin and $end

Query for events with a date and time greater than now

all - fairly simple query question that's been hounding me: How do I query for entries with a date and time only greater than now, or when the query is run (page requested)?
I've seen some examples but they aren't good enough for me to modify. Here's my code:
$todaysDate = date("Y-m-d h:i:s");
$params = array('select'=>'*', 'limit'=>3, 'orderby'=>'t.event_StartDate ASC', 't.event_StartDate < "$todaysDate"' );
An example of the variable "t.event_StartDate" outputs "2010-12-10 22:18:42" so I assume that may be how it's saved in the database.
I suspect I'm not building the date correctly or I need to be using a time function I'm not familiar with in MySQL. Help? This is for outputting a series of events with date and time.
I think you reverse the use <, it should be >
try
SELECT ... WHERE t.event_StartDate>NOW();
/* you don't even need to set $todaysDate */
t.event_StartDate > NOW() don't will returns nothing? a date higher of now lol. I'm confused.

Categories