I have a MySQL database with a date column.
I create a variable of the value in PHP like this:
$query = mysql_query ("SELECT customer_date FROM customers WHERE customer_id = {$_SESSION['session_id']}");
while ($result = mysql_fetch_object($query)) {
$date = $result->customer_date;
}
I need to convert the $datefrom YYYY-MM-DD to three variables
$yearvalue (for example 2012)
$monthname (for example August)
$dayvalue (for example 10)
And I need to be able to echo out anywhere in my code... How would I do this in a fancy way? I'm pretty new to coding...
Here:
while ($result = mysql_fetch_object($query)) {
$date = $result->customer_date;
$yearvalue = date("Y", strtotime($date) );
$monthname = date("F", strtotime($date) );
$dayvalue = date("d", strtotime($date) );
}
It'll only work/store the value of these values for the last row outputted from the $result.
how about this?
while ($result = mysql_fetch_object($query)) {
$date = $result->customer_date;
list($year,$month,$day,$hour,$minute,$second)=
explode('-',date('Y-F-d-h-i-s',strtotime($date)));
}
Also read this. You will need to play with Y-F-d-h-i-s as per your requirement.
Related
I need to be able to get the total amount spent either monthly or daily. To do that I do sum(tblaccounts.amountin) but the issue i'm having is I need to convert my date column to a different timezone fist. I've tried messing with convert_tz(date,"+00:00","+10:00") but not sure how to use it with LIKE.
How can I get records for monthly or daily based on the $period variable while first converting the timestamp?
Something like WHERE convert_tz(date) LIKE $date_to_check%
function check_limit($period='monthlylimit') {
if ($period == 'monthlylimit') {
$date_to_check = date("Y-m");
}
else { ### Day period
$date_to_check = date("Y-m-d");
}
$select = "SELECT
sum(tblaccounts.amountin) as amountin
FROM tblaccounts
WHERE date LIKE '" . $date_to_check . "%'";
}
Utilizing the timezone change inside mysql, this should work out:
if ($period == 'monthlylimit') {
$date = date('Ym');
$format = '%Y%m';
} else {
$date = date('Ymd');
$format = '%Y%m%d';
}
$sql = "SELECT SUM(t.amountin) as amountin FROM tblaccounts t WHERE
DATE_FORMAT(CONVERT_TZ(t.date,'+00:00','+10:00'),'". $format ."') = '". $date ."'";
The correct timezone numbers, will depend on what you have mysql defaulted too, and your desired result. You may have to twiddle with that number.
Or you can change the timezone for the date on php's side and skip mysql tz converting:
$dt = new DateTime("now", new DateTimeZone($tz));// $tz to equal what you are aiming for
$dt->setTimestamp(time());// might not be needed
if ($period == 'monthlylimit') {
$date = $dt->format('Ym');
$format = '%Y%m';
} else {
$date = $dt->format('Ymd');
$format = '%Y%m%d';
}
$sql = "SELECT SUM(t.amountin) as amountin FROM tblaccounts t WHERE
DATE_FORMAT(t.date,'". $format ."') = '". $date ."'";
Note: I did not use LIKE here, as that is why I introduced DATE_FORMAT to set it to a single value to compare on.
I'm passing the following value via URL to PHP:
&newtimestamp=2016-12-21%2014:44:44.
Instead of %20 I've tried with +.
In PHP I have this:
$newtimestamp = $_GET["newtimestamp"];
Which correctly shows the timestamp if I do:
echo ($newtimestamp);
But when trying:
echo date_format($newtimestamp,'U');
or
echo date_format($newtimestamp,'Y-m-d H:i:s');
I get no output at all. And later in the script, the input is used to compare against an SQL table:
$sql = ("SELECT sender,subject,timestamp,threadid,username,notify,msgtype FROM Messages WHERE sender = '$usernametmp' AND subject !='' AND timestamp > '$newtimestamp' ORDER BY timestamp");
And I get no results at all.
I do get results If I manually set the timestamp to
$newtimestamp = '1985-10-07 11:42:12';
I was thinking that I need to define it as datetime with:
$timestamp = new DateTime($newtimestamp);
But then I get a server error.
PHP version is 5.3, by the way. and needs to be changed by my hosting provider. If that's the solution, is there a lot of stuff running with 5.3 that will no longer work with 5.5 or 5.6 (this is what they offer)?
I hope someone can see what I'm doing wrong here, thanks in advance!
You need to use the date_create function and decode the URL on the GET like this:
<?php
$newtimestamp=date_create(urldecode($_GET['newtimestamp']));
echo date_format($newtimestamp,"Y/m/d H:i:s");
You cannot compare human time to unix time format, unix time looks like this
1483319956
So you probably need a function to help you do that
try this custom function i wrote
change_date_to_timestamp($date_string)
{
$array = explode(' ', $date_string);
$date = $array[0];
$date = explode('-', $date);
$year = (int)$date[0];
$month = (int)$date[1];
$day = (int)$date[2];
$hour = 00;
$minute = 00;
$second = 00;
if (isset($array[1])) {
$time = $array[1];
$time = explode(':', $time);
$hour = (int)$time[0];
$minute = (int)$time[1];
$second = (int)$time[2];
}
$stamp = mktime($hour, $minute, $second, $month, $day, $year);
return $stamp;
}
Refactor as pleased
I have a PHP script which records things based on the day. So it will have a weekly set of inputs you would enter.
I get the data correctly, but when i do $day ++; it will increment the day, going passed the end of the month without ticking the month.
example:
//12/29
//12/30
//12/31
//12/32
//12/33
Where it should look like
//12/29
//12/30
//12/31
//01/01
//01/02
My script is as follows:
$week = date ("Y-m-d", strtotime("last sunday"));
$day = $week;
$run = array(7); //this is actually defined in the data posted to the script, which is pretty much just getting the value of the array index for the query string.
foreach( $run as $key=>$value)
{
$num = $key + 1;
$items[] = "($num, $user, $value, 'run', '$day')";
echo "".$day;
$day ++;
}
Should I be manipulating the datetime differently for day incrementations?
You can use
$day = date("Y-m-d", strtotime($day . " +1 day"));
instead of
$day++;
See live demo in ideone
You refer to $day as a "datetime" but it is just a string - that is what date() returns. So when you do $day++ you are adding 1 to "2015-12-02". PHP will do everything it can to make "2015-12-02" into a number and then add 1 to it, which is not date math. Here is a simple example:
<?php
$name = "Fallenreaper1";
$name++;
echo $name
?>
This will output:
Fallenreaper2
This is how I would do it, using an appropriate data type (DateTime):
<?php
$day = new DateTime('last sunday');
$run = array(7);
foreach ($run as $key => $value) {
$num = $key + 1;
$dayStr = $day->format('Y-m-d');
$items[] = "($num, $user, $value, 'run', '$dayStr')";
echo $dayStr;
$day->modify('+1 day');
}
To increase time you should use strtotime("+1 day");
here is simple example of using it
<?php
$now_time = time();
for($i=1;$i<8;$i++) {
$now_time = strtotime("+1 day", $now_time);
echo date("Y-m-d", $now_time) . "<br>";
}
?>
I have tried every combo I can think of / found and no matter what I do, my codet echos the message even if the account isn't locked out:
<?php
$infosql = "SELECT * FROM premiersounds_users WHERE customer_id = $id";
$inforesult = mysql_query($infosql) or die(mysql_error());
$info = mysql_fetch_array($inforesult);
//Get current date from server
$format="%m/%d/%y";
$c_date=strftime($format);
//set sessions
$_SESSION['current_date'] = $c_date;
//The date in the database is 10/31/11
$_SESSION['lockout_date'] = $l_date;
//Check is Current date = lockout date
if ($c_date <= $l_date) {
header("location:documnet_editors/edit_weddingplanner.php?id=$id");
}
else {
echo 'Whoops! Were sorry your account has been locked to edits
because your event is less than 48 hours from now or your event has passed.
To make changes to your event please contact your DJ.';
}
?>
<?php
//Destroy Session for Lockout Date to prevent bypasses
unset($_SESSION['lockout_date']);
?>
If your $l_date is populated, and I don't think it is, if it is stored as MM/DD/YY, you'll want to use PHP's strtotime to convert it to a unix timestamp for quick comparison:
if( strtotime($db_date) >= time() )
{
// do something
}
I would suggest comparing timestamps instead of formatted dates:
<?php
$date_a = new DateTime();
$date_b = new DateTime('2000-10-20 00:10:20');
if ($date_a->getTimestamp() > $date_b->getTimestamp()) {
echo 1;
} else {
echo 0;
}
convert your dates to unixtime for more accurate comparison. Add this function to your code:
function unix_time($date){
$unix_date = str_replace("-","/",$date);
$unix_date = str_replace(".","/",$unix_date);
$unix_date = str_replace(" pm","",$unix_date);
$unix_date = str_replace(" am","",$unix_date);
$time = strtotime($unix_date);
return $time;
}
then convert the dates to unix:
$l_date = unix_time($_SESSION['lockout_date']);
$c_date = unix_time($_SESSION['current_date']);
or you can also get the date directly from the database:
$l_date = unix_time($info['date_in_database']);
compare the dates in unix format:
if ($c_date = $l_date) {
// your code here
}
this should work.
I use PHP to perform SQL to pull out some data from my database between a date range. The dates are stored as date in the relation:
$from = "2011-08-11";
$to = "2011 - 08- 25";
$query = mysql_query("SELECT date FROM `entries` WHERE date BETWEEN '$from' AND '$to' ORDER BY date ASC");
I would like to find the earliest date pulled from the relation.
If the query is successful, I store the 'date' attribute in a php array called $dates. I thought I could iterate over this $dates and compare the $date values after converting them into dates.
if($query){
$dates = array();
while($row = mysql_fetch_array($query)){
$dates[] = $row['date'];
}
$min = strftime("%Y-%m-%d", strtotime($dates[0]));
for($i = 1; $i < count($dates); $i++){
if($dates[i] < $min){
$min = $dates[i];
}
}
This does not work however...It prints random values....Perhaps there is a much simpler way to do this and I am overcomplicating matters...
HEEEELLLP!!
If you order your query, then it will be the first (or the last) row in you're query. So you wouldn't need to find it.
Instead of
$min = strftime("%Y-%m-%d", strtotime($dates[0]));
you should use
$min = date("%Y-%m-%d", strtotime($dates[0]));
The simplest way is to use the first date since you know it is already the earliest due to ASC in your SQL statement. After you read the rows into your array, just use the first element.
while($row = mysql_fetch_array($query)){
$dates[] = $row['date'];
}
$earliest_date = $dates[0];
If all you want to do is find just the earliest date, and you don't care about the rest, you could use the aggregate function min() in your query like so:
SELECT MIN(date) AS earliest FROM `entries` WHERE date BETWEEN '$from' AND '$to'
Then just grab the earliest column from the result set in your php code.
Convert the dates to numbers and sort the array?
Take what you have (lines 1-5),
foreach ($dates as $date) {
// convert each date from "YYYY-MM-DD" to "YYYYMMMDD" and turn it into an int
$date = intval(str_replace("-", "", $date));
}
// sort the array from lowest to highest
asort($dates);
// the minimum is the first item in the array
$minint = $date[0];
// convert back into "YYYY-MM-DD" format
$min = substr($minint, 0, 4) . "-" . substr($minint, 4, 6) . "-" . substr($minint, 6);