Reputation: 11011
I'm making a system to save users' IPs into a table along with the last time they posted something. First, I check for an already-existent record of the user's IP with
SELECT lastpost FROM users WHERE ip = '$IP'
I then check whether the result of that query is empty, and if it is it means that the user's IP is not present and it should be recorded, so I proceed by doing this query:
INSERT INTO users (ip, lastpost) VALUES ('$IP', '$ctime')
Where $IP
is the user's IP fetched using $_SERVER['REMOTE_ADDR']
and $ctime
is a time string created using date("Y-m-j H:i:s")
.
Even though after performing the latter query the data is present into the table, I keep getting the error
SQLSTATE[HY000]: General error
Which is, by itself, not very helpful. I'd like to understand what I'm doing wrong here. Thanks in advance.
P.S.: I'll use this question to also ask how I could compare, using a query, the time I have calculated with PHP's date()
with the time already present in the table (of type "datetime") to see if the one calculated with date()
is greater than the one in the database by at least one minute.
Upvotes: 1
Views: 1060
Reputation: 26
I would first try to cast $ctime
as a datetime CAST('$ctime' AS DATETIME)
to see if that works.
For testing minute difference use TIMEDIFF()
.
SELECT IF(TIMEDIFF(CAST('$ctime' AS DATETIME), lastpost) > CAST('00:01:00.000000' AS DATETIME), /*do this*/, /*else do this*/)
This will return a time difference. If the time difference is negative, $ctime
is earlier than lastpost. But you can get into pretty fine granularity here.
See if the above helps.
(Oh, I found all of this via Google and searching for mysql and datediff, timediff, or cast.)
Upvotes: 1