This query works fine:
$sql = "SELECT *
FROM `pricing_data`
WHERE `Label`='BTC'
AND `Timestamp` LIKE '2018-01-19 00:00:%'
LIMIT 1" ;
But this doesn't:
$date = date("Y-m-d ",strtotime("-1 days", time()))." 00:00:";
$to = "BTC" ;
$sql = "SELECT *
FROM `pricing_data`
WHERE `Label`='$to'
AND `Timestamp` LIKE '$date%'
LIMIT 1" ;
Any Solution?
Thanks.
The error is too small to look
there is an extra space in Y-m-d, because of which two spaces created in DateTime you created and query didn't worked.
$date = date("Y-m-d",strtotime("-1 days", time()))." 00:00:";
//..................^ remove space from here --------^ already have here
Check this output for more clarification:- https://eval.in/939013
Note:- Instead of adding hours and minutes manually do with date() itself like below:-
https://eval.in/939015
So finally code need to be:-
$date = date("Y-m-d 00:00:",strtotime("-1 days", time()));
$to = "BTC" ;
$sql = "SELECT *
FROM `pricing_data`
WHERE `Label`='$to'
AND `Timestamp` LIKE '$date%'
LIMIT 1" ;
Related
I want to fetch all records between two dates from database in php. Date format is dd/mm/yyyy hh:mm:ss. example 06/Dec/2016 05:56:15
I'm using following code
$Sdate=date_create($_GET['sdate']);
$start=date_format($Sdate,"d/M/Y H:i:s");
$Edate=date_create($_GET['edate']);
$end=date_format($Edate,"d/M/Y H:i:s");
$sql = "SELECT * FROM `payments` WHERE `customerid` = '".$_SESSION['id']."' AND dateandtime BETWEEN ('".$start."', '".$end."') ORDER BY id DESC";
But this is not working
Thank You in advance for helping me
Try this:
$Sdate = date('Y-m-d H:i:s', strtotime($_GET['sdate']);
$Edate = date('Y-m-d H:i:s', strtotime($_GET['edate']);
$sql = "SELECT * FROM `payments`
WHERE `customerid` = '".$_SESSION['id']."'
AND dateandtime BETWEEN '$Sdate' AND '$Edate'
ORDER BY id DESC";
The correct syntax is:
dateField BETWEEN dateFieldLow AND dateFieldHigh
I have saved rows in my table with custom timezone.Now I want to retrieve data from those table for just today.
So here is what I tried
date_default_timezone_set('America/Los_Angeles');
$dt = new DateTime();
$today = $dt->format('Y-m-d'); //outputs 2015-12-07
$ok = mysqli_query($sqli,"SELECT * FROM `table` WHERE `date` = '$today'" );
And my row contains date in timestamp format like 2015-12-07 22:42:02
But I get empty result.
Try this:
$ok = mysqli_query($sqli,"SELECT * FROM `table` WHERE DATE(date) = CURDATE()" );
to convert time according to timezone: ConvertTimeZone
if $today='2015-12-07 22:42:02'; your query will give the result.
$today='2015-12-07 22:42:02';
$ok = mysqli_query($sqli,"SELECT * FROM `table` WHERE `date` = '$today'" );
else do pass the today date and next date and retrieve the value as given
$today='2015-12-07';
$next='2015-12-08';
$ok = mysqli_query($sqli,"SELECT * FROM `table` WHERE `date` >= '$today' and `date` <= '$next' " );
for more details refer this Oracle SQL : timestamps in where clause How to compare Timestamp in where clause
You should convert date to timestamp before passing it to mysql:
date_default_timezone_set('America/Los_Angeles');
$dt = new DateTime();
$today = $dt->format('Y-m-d'); //outputs 2015-12-07
$ok = outputs("SELECT * FROM `table` WHERE DATE_FORMAT(date,'%Y-%m-%d')= $today" );
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 am working on a file management project, where I have expiry dates for every file. I need to list all the files that are going to expire the next year. What will be the SQL query?
should it be something like:
$date = date ('Y-m-j');
$newdate = strtotime ( '+1 year' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
$sql = "SELECT * FROM `files` WHERE `expDate` = year ($newdate)" ;
Try:
$sql = "SELECT * FROM `files` WHERE YEAR(`expDate`) = YEAR(NOW()) + 1" ;
If the expDate is in mysql timestamp(yyyy-mm-dd hh:mm:ss) , you can use this
DATE_ADD(`expDate`, INTERVAL 1 YEAR)
Try this
$newdate = date ( 'Y-m-j' , strtotime('+1 year') );
$sql = "SELECT * FROM `files` WHERE `expDate` = year ($newdate)" ;
or
$sql = "SELECT * FROM `files` WHERE `expDate` = YEAR(NOW())+1;
you can use mysql DATE_ADD to add years
$sql = "SELECT * FROM `files` WHERE `expDate` = YEAR(DATE_ADD($date, INTERVAL 1 YEAR))";
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 ''.