This question already exists:
SQL order by date, time [duplicate]
Closed 9 years ago.
I have table named notify with (seeker, donor, date) columns
the date column of type (datetime) and it stores the following format YYYY-MM-DD HH:MM:SS I'm trying to SELECT 1 record with the latest date from notify table and then compare the date with the current date and calculate the number of days between tow dates..
<?php
session_start();
$email = $_GET['email'];
date_default_timezone_set('Asia/Riyadh');
$time = date("Y-m-d H:i:s");
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']."'AND donor='".$email."' ORDER_BY `date` DESC LIMIT 1";
$st = $conn->prepare($note);
$st->execute();
if($found = $st->fetch(PDO::FETCH_ASSOC)){
$now = $time;
$old_date = strtotime($found['date']);
$dateif = $now - $old_date;
if(floor($dateif/(60*60*24)) >= 7){
echo "the difference between tow dates is 7 days or more";
} else { echo "difference between tow dates is less than 7 days";}
}
?>
the code is not working ! i have only one record in my notify table with this value in date 2013-04-22 09:15:47
First of all, you should use prepared statements like this:
$note = "SELECT *
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
Without the place holders you're still open to SQL injection.
Second, you can't compare a string with an integer in this way:
$now = $time; // string
$old_date = strtotime($found['date']); // integer
$dateif = $now - $old_date; // dunno?
You should compare apples with apples:
$seven_days_ago = strtotime('-7 days');
$old_date = strtotime($found['date']);
if ($old_date > $seven_days_ago) {
echo "difference between tow dates is less than 7 days";
} else {
echo "the difference between tow dates is 7 days or more";
}
Since your date column doesn't exist, there's no point in ordering by it. Also, you're exposed to SQL injection in the case where $_SESSION['email'] is not secured.
So, the correct form would be to use prepared statements, as well as order by the right column. (assuming PDO, you can use mysqli as well):
/** #var PDO $pdo - Assuming a PDO connection. */
$query = "SELECT * FROM `user` WHERE `ID` = :email ORDER BY `time` DESC";
$stmt = $pdo->prepare($query);
$stmt->execute(array($_SESSION['email']));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); //Get all results in an associated array form.
Jack's answer shows you how to use prepared statements correctly. Here is the code to simplify the date calculation using DATEDIFF().
$note = "SELECT *, DATEDIFF(NOW(), `date`) AS date_diff
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER_BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
$row = $st->fetch(PDO::FETCH_ASSOC);
// do something with $row
If you are attching any variables to string then you need to concatinate them using dot and oder by will come after where condition and inside $_SESSION you missed quotes
$query = "SELECT * FROM user WHERE ID='".$_SESSION['email']."' ORDER_BY date, time";
For retrieving latest date from database please try executing following sql query
$query="SELECT * FROM user WHERE ID='".mysql_real_escape_string($_SESSION[email])."' ORDER_BY date,time desc limit 1";
In order to retrieve latest date you need to sort field for date in descending order
$note = "SELECT * FROM notify WHERE seeker=' ".$_SESSION['email']. " ' AND donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
have you try to order by desc? as shown bellow:
$note = "SELECT * FROM notify
WHERE
seeker=' ".$_SESSION['email']. " '
AND
donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
you forgot ` here around date. date is reserved word in mysql,
if you want to use it as column name place ` around it.
EDIT also you have extra space remove it
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']. "'
AND donor='".$email."' ORDER_BY `date` LIMIT 1";
Related
In my table i have date records like 02-04-2016 , 03-01-2016 and 04-01-2016 if i am on 03-01-2016 i want the previous record which is 02-01-2016 But it gives me 01-01-2016 which is the first record of my table. No matter what date i am on.
if(isset($_POST['place'])){
$place = $_POST['place'];
$date = date("Y-m-d", strtotime($_POST['date']));
$classtype = $_POST['classtype'];
$getdate = mysql_query("SELECT * FROM `class` WHERE `city`='$place' AND `clastype`='$classtype' AND `classdate`<'$date' limit 0,1")or die(mysql_error());
$mydt = mysql_fetch_array($getdate);
$mdt = date("d-m-Y", strtotime($mydt[classdate]));
echo $mdt;
}
"SELECT * FROM `class` WHERE `city`='$place' AND `clastype`='$classtype' AND `classdate`<'$date' order by `classdate` desc limit 0,1"
Please use order by clause.
Use ORDER BY clause
Try this:
SELECT *
FROM `class`
WHERE `city`='$place' AND `clastype`='$classtype' AND
`classdate`<'$date'
ORDER BY id DESC
LIMIT 0,1
I have a sql query which has an if..else function. if the submit button is clicked, it will perform the particular query. else, the query will take in the first 20 dates in my database. however, i am not sure how to do the else query statement to take up only the first 20 dates. do help, thank you :)
<?php
$server = "localhost";
$user = "root";
$password = "";
$database = "sensors_database";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
if(isset($_POST["usub"])){
$date1 = $_POST["datepicker"];
$date2 = $_POST["datepicker1"];
$query1 = "SELECT time, Ultrasonic FROM pi_sensors_network WHERE date BETWEEN '".$date1."' AND '".$date2."'";
$result1 = mysql_query($query1);
while($row = mysql_fetch_assoc($result1))
{
$dataset1[] = array(strtotime($row['time'])*1000,$row['Ultrasonic']);
//echo strtotime($row['time'])*1000;
}
}
else {
}
?>
Here you go:
SELECT `time`, `Ultrasonic` FROM `pi_sensors_network`
WHERE 1=1 ORDER BY `date` ASC LIMIT 0,20
If you are asking between the dates you mentioned in the query, then use
limit
$query1 = "SELECT time, Ultrasonic FROM pi_sensors_network WHERE date BETWEEN '".$date1."' AND '".$date2."' limit 0,20";
First Create index on table < pi_sensors_network > on column < date >
CREATE INDEX pi_sensors_network01 ON pi_sensors_network (`date`);
Then,
SELECT
`time`,`Ultrasonic`
FROM
pi_sensors_network
WHERE
`date` IN ( SELECT `date` FROM
(SELECT DISTINCT(`date`)
FROM pi_sensors_network
ORDER BY `date` ASC LIMIT 0,20)
AS tmp ) ;
If your table is too large, This query may take long even after indexing,
In this case,
I'ld suggest you to make an array of first 20 dates by separate query and then implode it in your main query !
Im trying to do a mysql check if a record from $uid exist from today based on $timestamp and if it doesnt then do an INSERT.
//EXAMPLE RECORD FROM TABLE VOTE
--- #vote_fb_uid# --- #vote_time#
665414807 1369219044
tjt
//STEP 1 - do a look up on $uid and check with timestamp $today
$timestamp = $this->time;
$date = date('Y-m-d', $timestamp);
$today = date('Y-m-d');
$sql = "
SELECT * FROM vote WHERE
vote_fb_uid = '$this->fb_uid',
WHERE vote_time = '$CHECK_IF_THERE_IS_AN_ENTRY_FROM_TODAY'";
$res = mysql_query($sql) or die( mysql_error());
//STEP 2 - If no records are found for today - then we do an INSERT
if($no_record_for_today) {
$sql = sprintf("
INSERT INTO vote(
vote_fb_uid,
vote_time)
VALUES ('%s','%s')",
mysql_real_escape_string($this->fb_uid),
mysql_real_escape_string($this->time));
$res = mysql_query($sql) or die( mysql_error());
}
Obviously im strugling with the SQL part for the look up - im wondering if there isnt some in-built SQL function to do this or similar?
to check if you had a vote in the last 24 hours :
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND FROM_UNIXTIME(vote_time) >= DATE_SUB(NOW(), INTERVAL 1 DAY)
if you want to limit to the same day (mean you are allowed to post at 2013.05.21 23:55 and 2013.05.22 00:05)
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND DATE(FROM_UNIXTIME(vote_time)) = DATE(NOW())
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.
mysql> SELECT CURDATE();
-> '2008-06-13'
mysql> SELECT CURDATE() + 0;
-> 20080613
Try this:
$today = date('Y-m-d'); //change it to timestamp if you want in timestamp
$sql = "
SELECT count(*) as total FROM vote WHERE
vote_fb_uid = '$this->fb_uid' and
vote_time = '$today'";
$res = mysql_query($sql) or die( mysql_error());
if($res[0]['total'] < 1){
$sql = sprintf("
INSERT INTO vote(
vote_fb_uid,
vote_time)
VALUES ('%s','%s')",
mysql_real_escape_string($this->fb_uid),
mysql_real_escape_string($this->time));
$res = mysql_query($sql) or die( mysql_error());
} else{
//return error("custom","","Already Inserted.");
echo "already inserted";
}
Your $sql query have a syntax error, you have used two times clause WHERE the correct syntax to use two or more clauses in where is using AND to join them, to get only record wich don't have an entry for today you can use DATE_SUB with 1 day interval
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid',
AND vote_time <= DATE_SUB(vote_time, INTERVAL 1 DAY)
This question already exists:
SQL order by date, time [duplicate]
Closed 9 years ago.
I have table named notify with (seeker, donor, date) columns
the date column of type (datetime) and it stores the following format YYYY-MM-DD HH:MM:SS I'm trying to SELECT 1 record with the latest date from notify table and then compare the date with the current date and calculate the number of days between tow dates..
<?php
session_start();
$email = $_GET['email'];
date_default_timezone_set('Asia/Riyadh');
$time = date("Y-m-d H:i:s");
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']."'AND donor='".$email."' ORDER_BY `date` DESC LIMIT 1";
$st = $conn->prepare($note);
$st->execute();
if($found = $st->fetch(PDO::FETCH_ASSOC)){
$now = $time;
$old_date = strtotime($found['date']);
$dateif = $now - $old_date;
if(floor($dateif/(60*60*24)) >= 7){
echo "the difference between tow dates is 7 days or more";
} else { echo "difference between tow dates is less than 7 days";}
}
?>
the code is not working ! i have only one record in my notify table with this value in date 2013-04-22 09:15:47
First of all, you should use prepared statements like this:
$note = "SELECT *
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
Without the place holders you're still open to SQL injection.
Second, you can't compare a string with an integer in this way:
$now = $time; // string
$old_date = strtotime($found['date']); // integer
$dateif = $now - $old_date; // dunno?
You should compare apples with apples:
$seven_days_ago = strtotime('-7 days');
$old_date = strtotime($found['date']);
if ($old_date > $seven_days_ago) {
echo "difference between tow dates is less than 7 days";
} else {
echo "the difference between tow dates is 7 days or more";
}
Since your date column doesn't exist, there's no point in ordering by it. Also, you're exposed to SQL injection in the case where $_SESSION['email'] is not secured.
So, the correct form would be to use prepared statements, as well as order by the right column. (assuming PDO, you can use mysqli as well):
/** #var PDO $pdo - Assuming a PDO connection. */
$query = "SELECT * FROM `user` WHERE `ID` = :email ORDER BY `time` DESC";
$stmt = $pdo->prepare($query);
$stmt->execute(array($_SESSION['email']));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); //Get all results in an associated array form.
Jack's answer shows you how to use prepared statements correctly. Here is the code to simplify the date calculation using DATEDIFF().
$note = "SELECT *, DATEDIFF(NOW(), `date`) AS date_diff
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER_BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
$row = $st->fetch(PDO::FETCH_ASSOC);
// do something with $row
If you are attching any variables to string then you need to concatinate them using dot and oder by will come after where condition and inside $_SESSION you missed quotes
$query = "SELECT * FROM user WHERE ID='".$_SESSION['email']."' ORDER_BY date, time";
For retrieving latest date from database please try executing following sql query
$query="SELECT * FROM user WHERE ID='".mysql_real_escape_string($_SESSION[email])."' ORDER_BY date,time desc limit 1";
In order to retrieve latest date you need to sort field for date in descending order
$note = "SELECT * FROM notify WHERE seeker=' ".$_SESSION['email']. " ' AND donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
have you try to order by desc? as shown bellow:
$note = "SELECT * FROM notify
WHERE
seeker=' ".$_SESSION['email']. " '
AND
donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
you forgot ` here around date. date is reserved word in mysql,
if you want to use it as column name place ` around it.
EDIT also you have extra space remove it
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']. "'
AND donor='".$email."' ORDER_BY `date` LIMIT 1";
I have this table :
I would like to delete same rows. For example first five rows are the same, my table should have only one row that includes this data : 40.792274 29.412994 2011-12-21 17:19:52.
So I used the following code :
$query = "SELECT * FROM table GROUP BY date";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$date = $row['date'];
$lat = $row['latitude'];
$lon = $row['longitude'];
$query = "SELECT * FROM table WHERE date='$date' AND latitude='$lat' AND longitude='$lon'";
$re = mysql_query($query);
$number = mysql_num_rows($re);
$number--;
$query = "DELETE * FROM table WHERE date='$date' AND latitude='$lat' AND longitude='$lon' LIMIT $number";
mysql_query($query);
}
But this code doesn't work.. What should I do ?
Edited :
I solved my question :
$query = "SELECT * FROM table GROUP BY date";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$date = $row['date'];
$lat = $row['latitude'];
$lon = $row['longitude'];
$query = "SELECT * FROM table WHERE date='$date' AND latitude=$lat AND longitude=$lon";
$re = mysql_query($query);
$number = mysql_num_rows($re);
$number--;
$query = "DELETE FROM table WHERE date='$date' AND latitude=$lat AND longitude=$lon LIMIT $number";
mysql_query($query);
}
Query lines were incorrect in my first question.
To remove the duplicate elements, you would use something like this:
$q = "SELECT date FROM table GROUP BY date"
$r = mysql_query($r);
$date = '';
while($row = mysql_fetch_array($r)){
$date = $row['date'];
$q = "SELECT date FROM mytable WHERE date='$date'";
$re = mysql_query($q);
$num = mysql_num_rows($re);
$num--;
$q = "DROP FROM mytable WHERE date='$date' LIMIT $num";
mysql_query($q);
}
Should do the trick. More specifically, when creating your $date value, you have to provide PHP with a time to use. date() defaults to using the current time, but you can provide it with a custom time as the second argument.
I suggest you take a look at the strtotime() manual at php.net as well (To translate times in your db to timestamps that can be used with date() ).
EDIT: The Answer above has been edited to remove all duplicate entries.
Try changing $dateOfNewData = date('Y-m-d H:i:s');
to
$dateOfNewData = date('Y-m-d 00:00:00'); //or change the first 00 to H if you need it to match by hour, second 00 to i if you need to match minutes and the same with seconds.
or $dateOfNewData = date('Y-m-d') which is pretty much the same and works with datetime field types
And you also need to modify your query to something like this unless you need an exact time:
"SELECT * FROM mytable WHERE date = '$dateOfNewData'" // you might also want the end date if you're working with the past in your database.
Well you can try like "Ignas" suggest but you cal also try this:
First just get the date (year, month, day) without hour, minutes and seconds. If you use full date format then you need to match exactly the same time. (to second the same) which is not really what you are looking for i guess. So you can use this:
$dateOfNewData = date('Y-m-d'); //just get year, month, day in right format (2011-12-20)
Then run a query. Here you have more options but i think the easier is something like that:
"SELECT * FROM mytable WHERE date_col LIKE '$dateOfNewData%' GROUP BY date_col"
This will group the same dates together and will display just once and will match all the rows where 'date_col starts with example: 2011-12-20% (thats why i use LIKE and $dateOfNewData%)
$dateOfNewData contains current date in this format:year-month-day (2011-12-20) and in Mysql query dont forget to use % at the end of the date. It's like * in windows for example.
'mytable' replace with your table name and 'date_col' with date column.
date() you have used will give current date time , so try to use mktime() to get extact date time you want.
you have to change your query little bit, I have modified query below,
$query = mysql_query("SELECT * FROM mytable WHERE date='$dateOfNewData'");
In mysql Date or datetime coulmn should be within ''.