I have a sql table : date (Y-m-d) / time (00:00:00) / power (INT)
When I select a date from an inline datepicker, I am trying to post 3 HighCharts graph (one-24 hours, two-31 days of month, three-12 months of year) and I need to get the values out of the table for the chart to be created.
For the day, I need the 24 values for each hour '100,200,300,200,300 etc..'
Here is the PHP for the "day" but it is not working...
<?php
$choice = (isset($_POST['choice']))
? date("Y-m-d",strtotime($_POST['choice']))
: date("Y-m-d");
$con = mysql_connect("localhost","root","xxxxxx");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("inverters", $con);
$sql = "SELECT HOUR(time), COUNT(power)
FROM feed
WHERE time = DATE_SUB('".$choice."', INTERVAL 24 HOUR)
GROUP BY HOUR(time)
ORDER BY HOUR(time)";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
echo $row['choice'].'<br />';
?>
This has been confirmed by another individual that the code does not work, would anyone have a helpful solution to fix the error ?
Alan
At the moment, your SELECT gives you only the results which happened exactly 24 hours before the current moment. What you need is a range. Example for 1 hour (indentation added for clarity):
WHERE `time` BETWEEN
DATE_SUB('".$choice."', INTERVAL 24 HOUR)
AND DATE_SUB('".$choice."', INTERVAL 23 HOUR)
This way, you'll get results with time in the 1-hour range of "now - 24 hours" and "now - 23 hours". The BETWEEN operator is equivalent to this:
WHERE `time` >= DATE_SUB('".$choice."', INTERVAL 24 HOUR)
AND `time` <= DATE_SUB('".$choice."', INTERVAL 23 HOUR)
You need a loop to walk over the rows:
$sql = "
SELECT HOUR(time) as h, power
FROM feed
WHERE date = '".$choice."'
ORDER BY HOUR(time)";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
while($row = mysql_fetch_assoc($res)) {
echo $row['h'].":".$row['power']'<br />';
}
This will give you the power per day for a given month:
$sql = "
SELECT DAY(date) as d, SUM(power) as powerday
FROM feed
WHERE MONTH(date) = '".$month."'
GROUP BY DAY(date)
ORDER BY DAY(date)";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
while($row = mysql_fetch_assoc($res)) {
echo $row['d'].":".$row['powerday']'<br />';
}
Thank you everyone for all your help !
The problem was in the first string, I only had to change the date format in addition to your wonderful examles !
$choice = (isset($_POST['choice'])) ? date("m",strtotime($_POST['choice'])) : date("m");
Thank You Very Much !
Alan
Related
OK! So, I have a page where I'm trying to pull a list of records from the database with dates < 30 days from expiration.
Now, the tricky part is - that the date format is in "yyyy-mm-dd hh:mm:ss"
Here's my code:
$Today = date("Y-m-d h:i:s");
if ($result = $mysqli->query("SELECT * FROM table WHERE DATEDIFF(ExpireDate, '$Today') < 30 ORDER BY `StartDate` ASC"))
{
while($row = mysqli_fetch_array($result))
{
//show records
//this type of query usually works when I'm NOT doing stuff with dates
}
mysqli_close($mysqli);
}
When I try to pull just records without any date/time conditions, it gives me the entire list of records, but when I want to see the those conditions, it doesn't display anything.
How do I show the records that are 30 days from expiration?
I SHOULD NOTE - that this is for internal use, only, and that there is no access from the outside world.
(I just wanted something simple for internal records keeping)
I've even tried this:
select * from table where some_date < curdate() - interval 30 day
and failed miserably... thoughts?
Just let the > & < operators take care of it
$Today = date("Y-m-d h:i:s");
$ExpiresFromToday= date("Y-m-d h:i:s", strtotime("+30 days"));
if ($result = $mysqli->query("SELECT * FROM `table` WHERE (`ExpireDate` < '$ExpiresFromToday' AND `ExpireDate` > '$Today') ORDER BY `StartDate` ASC")){
while($row = mysqli_fetch_array($result)){
//show records
}
mysqli_close($mysqli);
}
EDIT
to work with DATEDIFF tell mysql to treat the datetime string as a date:
$Today = date("Y-m-d h:i:s");
if ($result = $mysqli->query("SELECT * FROM `table` WHERE (DATEDIFF(DATE(`ExpireDate`), DATE('$Today')) < 30 AND `ExpireDate` >= '$Today') ORDER BY `StartDate` ASC")){
while($row = mysqli_fetch_array($result)){
//show records
}
mysqli_close($mysqli);
}
Using MySQLi and PHP I have a Query Like below and I need to store the orderdate field from MySQL newOrder table (with format of Datetime like 2014-06-15 22:12:00) into a PHP variable like $orderTime and then add 1 Hour to the Time.
<?PHP
include 'conconfig.php';
$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$query = "select * from newOrder WHERE orderdate < NOW() ORDER BY id DESC LIMIT 1";
if ($result = $con->query($query))
{
if ($result->num_rows > 0)
{}
else
{
$resultStr = 'Nothing found';
}}
}
$con->close();
is it possible something like inside the while loop?
$orderTime = $row['orderdate'];
$orderTime = $orderTime +1hour;
Thanks
Easily done with date() and strtotime():
$orderTime = date('Y-m-d H:i:s', strtotime($row['orderdate'] . '+ 1 hour'));
Update to answer question in comment:
To check if difference between $ordertime and current time is greater than 2 hours:
if (time() - strtotime($orderTime) > 7200) {
echo 'Difference is greater than 2 hours';
}
I've written some code to check if 2 days have passed using 2 dates, but it does not seem to work.
<?php
date_default_timezone_set('Europe/Amsterdam');
$_connection = mysqli_connect("localhost", "root", "root", "theater") or die("Error: " . mysqli_error());
$query = "SELECT * FROM Reservering";
$result = mysqli_query($_connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$res = strtotime($row['ReserveringsDatum']);
echo date('d-m-y', $res);
}
mysqli_close($_connection);
?>
$row['ReserveringsDatum'] is a date which looks like this: "07-01-14" (example).
For some reason the echo date('d-m-y', $res); shows me "14-01-07", which is just the day and year being reversed.
Edit:
For those wondering how it ended up, here is the working code:
<?php
date_default_timezone_set('Europe/Amsterdam');
$_connection = mysqli_connect("localhost", "root", "root", "theater") or die("Error: " . mysqli_error());
$query = "SELECT *, DATEDIFF(NOW(), DATE(ReserveringsDatum)) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2 ";
$result = mysqli_query($_connection, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['Betaalt'] == 'nee') {
$query2 = "DELETE FROM Reservering WHERE `ReserveringID` = '".$row['ReserveringID']."'";
mysqli_query($_connection, $query2);
}
}
mysqli_close($_connection);
?>
As said in the comment, i would make the selection within SQL. There is not need selecting all the rows and filter them in PHP. Its something better done in SQL.
Simple Example:
SELECT *, DATEDIFF(NOW(), ReserveringsDatum) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2
Make sure reserveringsdatum is a DATE, if its a TIMESTAMP you need to convert it to DATE.
SELECT *, DATEDIFF(NOW(), DATE(ReserveringsDatum)) 'age' FROM Reservering WHERE DATEDIFF(NOW(), ReserveringsDatum) > 2
Try this
$res = strtotime($row['ReserveringsID']);
$limit = strtotime($row['ReserveringsID']) + strtotime("+2 day", $res);
var_dump($res); var_dump($limit);
if($limit > $res) {
echo "2 days have passed";
} else {
echo "2 days have not yet passed";
}
I think you need to fix you're condition.
If you want to check if $res is more than two days you have to compare limit to the current time, instead of $res.
$res = strtotime($row['ReserveringsID']);
$limit = strtotime('+2 days', $res);
if($limit < time()) {
echo "2 days have passed";
} else {
echo "2 days have not yet passed";
}
Your problem is in this line
$limit = strtotime($row['ReserveringsID']) + $2days;
You need to add 2 days like this one
$res = strtotime($row['ReserveringsID']);
$limit = strtotime('+2 days', $res);
Working demo of adding 2 days to a date
https://eval.in/86632
How do I add 24 hours to a unix timestamp in php?
Adding days to a timestamp
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)
in my code below i subtract the previous date of the user john in the field name date_time
from the current date CURRENT_TIMESTAMP the variable $newdate echo the answer in seconds only how can i make it to display from seconds to minutes from minutes to hours then hours to days
$query1 = "
SELECT (CURRENT_TIMESTAMP - date_time) AS dnew, date_time
FROM user
WHERE name = 'john'
";
$result1 = mysql_query ($query1) or die('query error2');
$line = mysql_fetch_assoc($result1);
$newdate = $line[dnew];
echo "$newdate";
$query1 = "
SELECT (CURRENT_TIMESTAMP - date_time) * 60 AS dnew, date_time
FROM user
WHERE name = 'john'
";
use math ( * 60)