SQL check current day - php

I want to check if the current year/month/day/week/hour is the same as the dateTime saved in the db.
The current dateTime is: 2013-12-15 12:02:19
The db dateTime is: 2013-12-15 12:00:00
This is my query that checks the year/month/day/week:
$query_topics = mysql_query("SELECT * FROM topics WHERE day(startTime) = day(CURDATE()) and month(startTime) = month(CURDATE()) and day(startTime) = day(CURDATE()) and week(startTime) = week(CURDATE())") or die (mysql_error());
This one works but when I add hour to the query he will give me back null rows.
This is the query with year/month/day/week/hour:
$query_topics = mysql_query("SELECT * FROM topics WHERE day(startTime) = day(CURDATE()) and month(startTime) = month(CURDATE()) and day(startTime) = day(CURDATE()) and week(startTime) = week(CURDATE()) and hour(startTime) = hour(CURDATE())") or die (mysql_error());

Try replacing CURDATE() with NOW():
hour(NOW())

Related

query mysql date time with compare from now time and update a field on mysql

I need to check which plant are online so I'm thinking to compare last date time update to the current time if difference is less than 15 min the plant is online otherwise is offline
I have write this in php to make a query but all row change to online or offline what I'm doing wrong?
it seams that the update is done on all row of the database not only in the selected by the first query
$sql = "select * from PlantData where lastUpdate > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
$resultt = mysqli_query($connection, $sql);
//echo($resultt);
while ($roww = $resultt->fetch_array()) {
$rowws[] = $roww;
}
foreach($rowws as &$roww) {
$sqlupdate = "update PlantData set statusConnection = 'online'";
mysqli_query($connection, $sqlupdate);
}
$sql2 = "select * from PlantData where lastUpdate < DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
$resultt2 = mysqli_query($connection, $sql2);
//echo($resultt);
while ($roww2 = $resultt2->fetch_array()) {
$rowws2[] = $roww2;
}
foreach($rowws2 as &$roww2) {
$sqlupdate2 = "update PlantData set statusConnection = 'offline'";
mysqli_query($connection, $sqlupdate2);
}
thanks for support
Run the query in only once
UPDATE PlantData
SET
statusConnection = CASE
WHEN lastUpdate >= NOW() - INTERVAL 15 MINUTE THEN 'online'
WHEN lastUpdate < NOW() - INTERVAL 15 MINUTE THEN 'offline'
END;

Sum table1 Between $date1 and $date2 AND username Equals $user

hello im having some problem with this sum select does anyone know whats wrong with this, it seems that im getting no result from it
$result = mysql_query("SELECT SUM(total)
FROM table1 where date BETWEEN '".$date1." 00:00:00' AND '".$date2." 23:59:59' and username = ".$user."");
while($row=mysql_fetch_array($result))
{ $sum = $row['SUM(total)'];}
Try
$query = "SELECT SUM(total) AS result
FROM table1
WHERE DATE(date) BETWEEN '$date1' AND '$date2'
AND username = '$user'";
$con = \\your db connection string
$result = mysql_query($con,$query);
while($row=mysql_fetch_array($result))
{$sum = $row['result'];}

SELECT SUM with date variable, for prestashop

i'd like to have a result on PHP/MYSQL
I have a table ps_orders with price on total_paid
I need to ask total for all price in current date, i have dificult ti insert correct date. I'm stopping here, and do not works... thnaks
....
$date = date("Y-m-d");
$query = "SELECT SUM(total_paid) FROM ps_orders WHERE delivery_date = '%$date%'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo mysql_result($result, 0);
Try
$query = "SELECT SUM(total_paid) FROM ps_orders WHERE delivery_date = '$date'";
or
$query = "SELECT SUM(total_paid) FROM ps_orders WHERE delivery_date LIKE '%$date%'";
depending on how your delivery_date field is setup as well as what you are using in your $date variable (time stamp vs just m-d-y), your query up to the where clause looks okay, but you could also try:
SELECT SUM(total_paid)
FROM ps_orders
WHERE delivery_date = $date;
if you are using a datetime field for delevery_date, you'll have to go more in depth and use a range:
SELECT SUM(total_paid)
FROM ps_orders
where (delivery_date > $date
and deliver_date < $date +interval 1 day)
This link should also help you out quite a bit when working with date: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
You can use one of the following:
DATE function in mysql converts 2013-11-20 10:54:12 to 2013-11-20, i.e. truncated a time in date
$query = "SELECT SUM(total_paid) FROM ps_orders WHERE DATE(delivery_date) = '$date'";
or you use only one '%' after $date with using LIKE, so this value will be matched for dates like 2013-11-20 10:12:13 :
$query = "SELECT SUM(total_paid) FROM ps_orders WHERE delivery_date like '$date%'";
or use string mysql function SUBSTRING
$query = "SELECT SUM(total_paid) FROM ps_orders WHERE SUBSTRING(delivery_date1, 1, 10) = '$date'";
use datetime with time and BETWEEN mysql comparison operator:
$query = "SELECT SUM(total_paid) FROM ps_orders WHERE delivery_date1 between '$date 00:00:00' and '$date 23:59:59'

mysql check if uid record exist for today based on timestamp else do an insert

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)

I want to count all the rows for todays / yesterdays date based on a DATETIME - mysql+php

I have database "db2" with table "menjava"
In table menjava have "id", "author" and "date_submitted" field
id - auto_increment
author - int(11)
date_submitted - datetime
I want to count all the rows for todays date and all the rows for yesterdays date (so there will be two codes with conditions) based on a DATETIME field called 'date_submitted' that holds the date and time of each record's creation.
In the file result.php, there is this count displayed, but it does not work. In the same file (result.php) I have some other code to display data from different database, so I think that povezava.php is working ok.
My code:
<?
require "povezava.php";
$q=mysql_query(" SELECT COUNT(*) AS total_number FROM menjava
WHERE date_submitted >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)",$link2);
// now you can
if ( $nt = mysql_fetch_array($q)){
echo $nt["total_number"];
$q=mysql_query($nt) or die(mysql_error());
}
?>
my file povezava.php looks like this:
<?
$servername='localhost';
$dbusername='user';
$dbpassword='pass';
$dbname1='db1';
$dbname2='db2';
$link1 = connecttodb($servername,$dbname1,$dbusername,$dbpassword);
$link2 = connecttodb($servername,$dbname2,$dbusername,$dbpassword);
function connecttodb($servername,$dbname,$dbusername,$dbpassword)
{
$link=mysql_connect ("$servername","$dbusername","$dbpassword",TRUE);
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
return $link;
}
?>
Error that I get:
A PHP Error was encountered
Severity: NoticeMessage: Array to string conversionFilename: templates/master.phpLine Number: 231 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Array' at line 1
Fixed:
<?
require "povezava.php";
$q=mysql_query("SELECT COUNT(*) AS total_number FROM menjava WHERE date_submitted >= DATE_SUB(CURRENT_DATE(), INTERVAL 0 DAY)",$link2);
// working
if ( $nt = mysql_fetch_array($q)){
echo $nt["total_number"];
}
?>
Thank you!
Try :
$q = 'SELECT COUNT(*) FROM menjava
WHERE date_submitted >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)';
$result = mysql_query($q);
$total_rows = mysql_fetch_row($result);
print $total_rows[0] . ' authors have been submitted today and yesterday.';
Please try the following SQL commands:
$sqlToday = "Select COUNT(*) FROM menjava WHERE DATE(date_submitted) = CURRENT_DATE()";
$sqlYesterday = "Select COUNT(*) FROM menjava WHERE DATE(dc_created) = CURDATE() - INTERVAL 1 DAY";
I use this function it's very simple
function statsofdays($database,$tableName,$coloneDate,$past_days_to_count=0)
{
$datenow = date("Y-m-d H:i:s");
$stringDays = "(SELECT COUNT(Id) FROM `".$tableName."` WHERE DAY(".$coloneDate.") = '".add_date_to_date($datenow,'0 days','d')."') as day1,";
for ($i=2; $i <= $past_days_to_count; $i++)
$stringDays .= "(SELECT COUNT(Id) FROM `".$tableName."` WHERE DAY(".$coloneDate.") = '".add_date_to_date($datenow,'-'.$i.' days','d')."') as day".$i.",";
$row = $database->query("SELECT ".$stringDays." (SELECT COUNT(Id) FROM `".$tableName."`) as total");
$stringReturn[0] = $row['total'];
$stringReturn[1] = $row['day1'];
for ($c=2; $c <= $past_days_to_count; $c++)
$stringReturn[$c] = $row['day'.$c];
return $stringReturn;
}
Params :
$database :
You can modify the function has your database structure, for me i use
a class load to use ->query()
$tableName :
The name of the table you want to get data from
$coloneDate
Name of date format fields
$past_days_to_count
Number of days to go back to the past (if == 0 you get a count of total rows and today rows)
Example
$stats_of_year = statsofdays( $database , "table_name" , "creation_date" , 365 );
return
total rows for each day for 365 days like example (the values >= 0)
using
echo $stats_of_year['total'];
echo $stats_of_year['day1'];
...
echo $stats_of_year['day365'];
you need this also :
function add_date_to_date($stringDate, $days, $stringFormat)
{
$date = date_create($stringDate);
date_add($date,date_interval_create_from_date_string($days));
return date_format($date,$stringFormat);
}

Categories