delete mysql records of a table after a minute - php

I need help for a simple question ,
$tme = date("Y-m-j H:i:s");
mysql_query("DELETE FROM PM_TABLE WHERE date <= $time - INTERVAL 60 SECOND");
So, It should work and delete all records old as long as long 1 minute.
But it cannot do the operation.
returning value would be like this :\
DELETE FROM PM_TABLE WHERE date <= 2011-07-28 08:49:29 - INTERVAL 60 SECOND
table schema :
CREATE TABLE IF NOT EXISTS `PM_TABLE` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`text` varchar(255) COLLATE utf8_bin NOT NULL,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)

The PHP variable is getting injected as a string, without single quotes to delimit it for SQL to interpret it correctly. But you don't need the PHP function - use:
mysql_query("DELETE FROM PM_TABLE
WHERE date <= NOW() - INTERVAL 60 SECOND");

Related

Select a record when the timestamp has passed by a certain amount of time MYSQL/PHP

I'm trying to select sessions that are younger than 6 hours old with this query like so:
"SELECT * FROM sessions WHERE members=1 AND ipRCreator != '$usn' AND tStamp < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 6 HOURS";
The problem is that the query condition is always false and never manages to find the sessions even when a record actually has a timeStamp of a few seconds ago.
obviously I am very sure that the problem is in the condition of the:
tStamp < DATE_SUB (CURRENT_TIMESTAMP, INTERVAL 6 HOURS)
I insert the data records in the table like this:
$timestamp = date("Y-m-d H:i:s");
$mysqli->query("INSERT INTO sessions (sessionId, members, ipRCreator, tStamp) VALUES('$sId', 1, '$usn', '$timestamp');") ;
I thought the problem was the formatting of the date but I don't think since the insert works well and the date is correctly inserted in the DB.
This is the sql structure of the table:
`sessionId` text NOT NULL,
`members` int NOT NULL,
`ipRCreator` text NOT NULL,
`gender` text CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
`age` int NOT NULL,
`tStamp` timestamp NOT NULL,
`id` int NOT NULL
Where could the problem be? Why does the condition never come true?
Sample record:
So as in this case, I'm trying to fetch this record since the timeStamp is less than 6 hours old with the query I showed; the problem is that the return query is null, it is as if there were no records that have a timeStamp younger than 6 hours (even if it is older it does not work)
To solve this problem I used this query:
SELECT * FROM sessions WHERE members=1 AND ipRCreator != '$usn' AND TIMEDIFF(CURRENT_TIMESTAMP, tStamp) < '06:00:00'

How to get rows from MySQL for the last 7 days?

How can I get the rows from table articles for the last 7 days?
Each row has a value timestmp where time is set via time().
I've tried this:
SELECT COUNT(*) FROM `articles` WHERE `timestmp`>NOW()-INTERVAL 168 HOUR
It doesn't work for me :(
The table is:
CREATE TABLE `articles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`link` text NOT NULL,
`article_name` text NOT NULL,
`descript` text NOT NULL,
`preview` text NOT NULL,
`content` text NOT NULL,
`category` int(11) NOT NULL,
`author` text NOT NULL,
`keywrds` text NOT NULL,
`timestmp` int(11) NOT NULL,
`modified` int(11) NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT (`keywrds`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
The expected output is all the articles for the last 7 days with names, descriptions and so on.
Your timestmp column should be storing a UNIX timestamp, which is the number of seconds since the start of the UNIX epoch in January 1, 1970. So, if you just want records which happened exactly within the last 7 days, then you may just subtract 7 days (as seconds) from your timestmp column:
SELECT COUNT(*) AS cnt
FROM articles
WHERE timestmp > UNIX_TIMESTAMP() - 7*24*60*60;
If instead, you want records from 7 days ago, including the entire first day, then we need to do more work. In this case, we have to compute midnight on the first day, then convert that to a UNIX timestamp.
SELECT COUNT(*) AS cnt
FROM articles
WHERE timestmp > UNIX_TIMESTAMP(DATE(NOW() - INTERVAL 7 DAY))

mySQL AND OR query inconsistant in results returned

I have a mysql query in php that is set to run hourly by a cron job. Sometimes the results are correct and sometimes I get back a result thats on a different date than being queried. As mysql is being run in a different timezone i am using php date() time() to correct the current hour and date. I first use count in mysql to every see if any records exist matching the criteria. And if they do i run the same query and grab the data. I am looking for records that are for the current day. Have a time frame of an hour or hour and a half ahead of the current time and match a couple other parameters being the JobStatus and TechID columns. Sometimes it runs correctly and sometimes I get records showing that are for days ahead. The column for the time in the database is a varchar as I just simply needed the current time to match a string as the appointment is entered into the database as 1PM or 9:30AM or whatever time slot was selected on the form in hour or half hour time frames. I have as well added my database structure below too. I have checked the database to see if its corrupt and it checks out fine.
Am I maybe going about this query incorrectly?
date_default_timezone_set("America/Chicago");
$SearchDate = date('Y-m-d', time());
//CURRENT TIME PLUS ONE HOUR
$TimePlusHour = date('gA', strtotime("+1 hours"));
//CURRENT TIME PLUS ONE HOUR PLUS SETTING MINUTES TO HALF HOUR
$Plus30 = date('g:30A', strtotime("+1 hours"));
$sqlCount = "SELECT COUNT(*) AS 'count' FROM ServiceTickets WHERE Date=
'".$SearchDate."' AND Time='".$Plus30."' OR Time='".$TimePlusHour."'
AND JobStatus='1' OR JobStatus='3' AND TechID= '".$TechID."' ";
$sql1 = "SELECT * FROM ServiceTickets WHERE Date= '".$SearchDate."' AND
Time='".$Plus30."' OR Time='".$TimePlusHour."' AND JobStatus='1' OR
JobStatus='3' AND TechID= '".$TechID."' ORDER BY id ASC";
Database structure
CREATE TABLE `ServiceTickets` (
`id` bigint(11) unsigned NOT NULL AUTO_INCREMENT,
`FirstName` varchar(255) DEFAULT NULL,
`LastName` varchar(255) DEFAULT NULL,
`Phone` varchar(20) DEFAULT NULL,
`Address` varchar(255) DEFAULT NULL,
`Address2` varchar(255) DEFAULT NULL,
`City` varchar(100) DEFAULT NULL,
`State` varchar(50) DEFAULT NULL,
`Zip` varchar(10) DEFAULT NULL,
`Email` varchar(255) DEFAULT NULL,
`Date` date DEFAULT NULL,
`Time` varchar(50) DEFAULT NULL,
`JobDesc` text,
`JobStatus` varchar(10) DEFAULT NULL,
`TechID` varchar(3) DEFAULT NULL,
`LastModified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
)
ENGINE=MyISAM AUTO_INCREMENT=21 DEFAULT CHARSET=latin1;
You are confusing your query when calling AND and OR, I would start by putting your OR in parentheses
$sqlCount = "SELECT COUNT(*) AS 'count' FROM ServiceTickets WHERE Date=
'".$SearchDate."' AND (Time='".$Plus30."' OR Time='".$TimePlusHour."')
AND (JobStatus='1' OR JobStatus='3') AND TechID= '".$TechID."' ";
$sql1 = "SELECT * FROM ServiceTickets WHERE Date= '".$SearchDate."' AND
(Time='".$Plus30."' OR Time='".$TimePlusHour."') AND (JobStatus='1' OR
JobStatus='3') AND TechID= '".$TechID."' ORDER BY id ASC";

MySQL query with time and random selecting

I'd like to know how to how to make a query that does this:
I have a table like this:
CREATE TABLE `sendingServers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`address` text NOT NULL,
`token` text NOT NULL,
`lastPoll` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And I'd like to get the following:
Select all servers where lastPoll is less then X seconds ago
Then select a random entry from the return value
Is this possible ? How do I achieve that ?
You can use something like this:
select * from `sendingServers`
where `lastPoll` > DATE_SUB(NOW(), INTERVAL 30 SECOND)
order by rand() limit 1

Get big result set from mysql

I've a big table with about 20 millions of rows and every day it grows up and I've a form which get a query from this table. Unfortunately query returns hundreds of thousands of rows.
Query is based on Time, and I need all records to classify them by 'clid' base on some rules.So I need all records to do some process on them to make a result table.
This is my table :
CREATE TABLE IF NOT EXISTS `cdr` (
`gid` bigint(20) NOT NULL AUTO_INCREMENT,
`prefix` varchar(20) NOT NULL DEFAULT '',
`id` bigint(20) NOT NULL,
`start` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`clid` varchar(80) NOT NULL DEFAULT '',
`duration` int(11) NOT NULL DEFAULT '0',
`service` varchar(20) NOT NULL DEFAULT '',
PRIMARY KEY (`gid`),
UNIQUE KEY `id` (`id`,`prefix`),
KEY `start` (`start`),
KEY `clid` (`clid`),
KEY `service` (`service`)
) ENGINE=InnoDB DEFAULT CHARSET=utf-8 ;
and this is my query :
SELECT * FROM `cdr`
WHERE
service = 'test' AND
`start` >= '2014-02-09 00:00:00' AND
`start` < '2014-02-10 00:00:00' AND
`duration` >= 10
Date period could be various from 1 hour to maybe 60 day or even more.(like :
DATE(start) BETWEEN '2013-02-02 00:00:00' AND '2014-02-03 00:00:00'
)
The result set has about 150,000 rows for every day. When i try to get result for bigger period or even one day database crashes.
Does anybody have any idea ?
I don't know how to prevent it from crashing, but one thing that I did with my large tables was partition them by date.
Here, I partition the rows by date, twice a month. As long as your query uses the partitioned column, it will only search the partitions containing the key. It will not do a full table scan.
CREATE TABLE `identity` (
`Reference` int(9) unsigned NOT NULL AUTO_INCREMENT,
...
`Reg_Date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`Reference`),
KEY `Reg_Date` (`Reg_Date`)
) ENGINE=InnoDB AUTO_INCREMENT=28424336 DEFAULT CHARSET=latin1
PARTITION BY RANGE COLUMNS (Reg_Date) (
PARTITION p20140201 VALUES LESS THAN ('2014-02-01'),
PARTITION p20140214 VALUES LESS THAN ('2014-02-14'),
PARTITION p20140301 VALUES LESS THAN ('2014-03-01'),
PARTITION p20140315 VALUES LESS THAN ('2014-03-15'),
PARTITION p20140715 VALUES LESS THAN (MAXVALUE)
);
So basically, you just do a dump of the table, create it with partitions and then import the data into it.

Categories