How to form this zend_db_select statement to compare timestamp - php

This is what i am trying to do.
id ip timestamp userid
9 127.0.0.1 2013-06-27 16:52:49 35
I would like to first query table to see if ip for the user is persisted. If so, he/she voted 2) Check timestamp of vote against current timestamp, if his voting time is way after 24 hours, then allow him to vote again. Ensure he can only vote once in 24 hours.
This is my current zend_db_select statement. Has some problems coming out with the logic
function checkIfCanLikeH($hlid,$ip){
$canlike = false;
$currenttime = time();
$checkquery = $this->dbo->select()
->from("hl", array("num"=>"COUNT(*)"))
->where("hlid = ?", $hlid)
->where("ip = ?", $ip)
->where("timestamp < ".new Zend_Db_Expr('NOW()'));
$this->dbo->setFetchMode(Zend_Db::FETCH_ASSOC);
$checkrequest = $this->dbo->fetchRow($checkquery);
if($checkrequest['num']!=0){
$ip = true;
}
return $ip;
}
I am stucked at how do i compare the timestamp. I need retrieve the timestamp from table and check if the current time is smaller than value in table (added 24 hours).
Advice appreciated.

->where("timestamp < DATE_SUB(NOW(), INTERVAL 1 DAY)");
This is the advantage of using MySQL's timestamp/datetime/date column types - you can use its inbuilt date and time functions. And I'm pretty sure you don't need Zend_Db_Expr here.
Edit: I'm not completely clear what you're asking, but I think the WHERE clause above does what you want, just the other way around. You could do this instead:
->where("DATE_ADD(timestamp, INTERVAL 1 DAY) < NOW()");
which is the same thing but written a different way. This means "where timestamp + 1 day is less than the current time".
If it helps, try running this query on your database:
SELECT DATE_ADD(timestamp, INTERVAL 1 DAY), NOW() FROM hl
so you can see how the DATE_ADD() function in MySQL works.

Related

MySQLi Prepared Statement to compare current time with stored datetime?

I have HTML form which I don't want users to be able to use more then once per day.
So far iv'e figured out what I should do but I'm not really sure how.
When a user submits the form I store their "IP" (column ip) aswell as the current time (column submitTime) and the current time + 23 hours (column releaseTime):
$submitDate = date("Y-m-d H:i:s");
$currentTime = time();
$releaseTime = date("Y-m-d H:i:s", strtotime('+23 hour', $currentTime));
But what I dont know is how can I proceed? I feel like I'm stuck.
I know I should compare $currentTime with the releaseTime I get from MySQL, but how?
So far I got this code (see the comment lines):
$ip = $_SERVER['REMOTE_ADDR'];
$stmt1 = $conn->prepare('SELECT * FROM IPlock WHERE ip=?') or die('Couldn\'t check the IP');
$stmt1->bind_param("s", $ip);
$stmt1->execute();
$stmt1->store_result();
$countRows = $stmt1->num_rows;
$stmt1->close();
if ($countRows > 0) {
/*
Code to check for how long the IP has existed in MySQL
If it has existed for more then 23 hours, remove it and proceed.
else abort (since its blacklisted for another x hours)
*/
}
I know I should not use the IP to identify an user since some users share their IP, but in this case I really have to.
You can use this to check if one has submitted the form in the last 24 hours.
SELECT * FROM IPlock WHERE `ip`=? AND `submitTime` > NOW() - INTERVAL 24 HOUR;
If IP has not submitted in the past 24 hours, no rows will be returned.
EDIT:
In addition to that, there's no need to use PHP date() function, you can do your insert like
INSERT INTO IPlock (`ip`, `submitTime`) VALUES ('127.0.0.1', NOW());
Note that CURRENT_TIMESTAMP will work just as well.
In fact, your problem is different from what you asked.
To compare a datetime value of mysql format you just have to compare it - not a big deal.
The real question is how to get the value for comparison (with your current code you can't) and what to do if you found that the record is outdated.
So, first you need to fetch the datetime value:
$stmt1 = $conn->prepare('SELECT releaseTime FROM IPlock WHERE ip=?');//never use die()
$stmt1->bind_param("s", $_SERVER['REMOTE_ADDR']);
$stmt1->execute();
$stmt1->store_result();
$stmt1->bind_result($releaseTime);
$stmt1->fetch();
and now you can start checking the date. Note that you don't need the num rows here.
if ($releaseTime > date("Y-m-d H:i:s")) {
/*
Code to check for how long the IP has existed in MySQL
If it has existed for more then 23 hours, remove it and proceed.
else abort (since its blacklisted for another x hours)
*/
}

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 :)

PHP querying MySQL, showing "count(*)"

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

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

How do you check time in a DB to todays date?

I'm trying to write a conditional that would check a date in a table. If the date in the table is the same as todays date, it would ignore. If not it wouldn't break.
if(strtotime($row['timefield']) == (date(Y-m-d)){
break 1;
}
^ This doesn't work but it's sort of what I am trying to do. Thoughts?
You can just do it on the database side if your database is using the local time/date.
(Assuming MySQL, and timefield is a date type):
SELECT
CASE
WHEN timefield = CURDATE()
THEN 1
ELSE 0
AS is_today
If timefield is datetime then:
SELECT
CASE
WHEN DATE(timefield) = CURDATE()
THEN 1
ELSE 0
AS is_today
Assuming the timefield is of DATE type:
if (strtotime($row['timefield']) != date('Y-m-d')){
// Do insert
}
I'm pretty sure the problem is in the formatting of your datetime. Instead compere something that is much for comparable and rigid, like unix timestamp.
So basically what NullPointer just said... Damn that was quick :D

Categories