I was wondering what is the best way to write the where statement in PHP where targetDate < Date.Now - HardCodedHours in PHP
If you mean how to do it in an MySQL query:
SELECT * FROM table WHERE targetDate <= date_sub(now(), interval 1 hour);
This will pull "field1" from table "myTable" where a DATETIME column "targetDate" is older than 12 hours.
$hardcodedHours = 12;
$sql = "SELECT field1 FROM myTable WHERE targetDate <= '" . date('Y-m-d H:i:s', strtotime("-$hardcodedHours hours")) . "'";
$result = mysql_query($sql);
$limitTime = time() - $nbHours * 3600;
$query = "SELECT ... WHERE TIMESTAMP(targetDate) < $limitTime;";
Or something like that.
Related
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'm trying to loop through every day in a month and get the number of results for each day in one month.
I've done the following;
<?php
include 'inclues/db.inc.php';
for($i = 2; $i < 30; $i++){
$date2 = $i-1;
$date1 = $i;
$q = mysql_query("SELECT * FROM `table` WHERE `date` < '2012-09-".$date1." 00:00:00' AND `date` > '2012-09-".$date2." 00:00:00'";
//$r = mysql_fetch_assoc($q);
echo mysql_num_rows($q)."<br />";
}
?>
It works if I just try to echo out dates 1 and 2 but not if I use the query.. I end up with a 500 internal server error when using the query.
Any ideas on how to resolve this? Is it generally bad practice to use a query within a loop?
Just execute
SELECT date, COUNT(*) from table group by date
SELECT * FROM `table` WHERE `date` BETWEEN $date1 AND $date2;
It's not bad practice to use a query within a loop.
Check what your query-string is becomming, try running that query manually on your db. It probably produses some error.
$sql = "SELECT * FROM `table` WHERE `date` < '2012-09-".$date1." 00:00:00' AND `date` > '2012-09-".$date2." 00:00:00'";
echo $sql;
$q = mysql_query($sql);
I'm trying to develop a simple php based schedule ...
This is my database table:
Let's say that current time/date is: 2012-03-21 02:00:00
PHP script should echo: Meeting 2
I have a part of the script, but no idea what to do next
<?php
$con = mysql_connect("localhost","root","");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_select_db("schedule", $con);
$current_time = date("Y-m-d H:i:s");
$result = mysql_query("SELECT * FROM events");
while($row = mysql_fetch_array($result)){
echo $row['Subject'];
}
mysql_close($con);
?>
How to filter query, to mach current time and scheduled subject? Thank you!
(if current_time is between StartTime and EndTime - echo it's Subject)
Try this query
SELECT * FROM events WHERE NOW() BETWEEN StartTime AND EndTime
Try select * from events where StartTime <= NOW() and EndTime >= NOW()
NOW() will give you current time in mysql.
Please try the following query
select * from events where current_time between startTime and endTime
Your query should like this
$result = mysql_query("SELECT * FROM events WHERE current_time between startTime and endTime);
The mysql BETWEEN operator may be of some use.
$startDate = gmdate('Y/m/d/ H:i:s','2012-03-21 02:00:00');
$endDate = gmdate('Y/m/d/ H:i:s','2012-03-21 02:23:59');
$sql = 'select subject from events
where startTime between "'.gmdate("Y/m/d H:i:s", $startDate) .
'" and "' . gmdate("Y/m/d H:i:s", $endDate).'") ';
Firstly, you're going to have to convert your StartTime and EndTime into a timestamp using strtotime so you can compare it to the current time (same thing goes for current time):
http://php.net/manual/en/function.strtotime.php
Then just say if current_time > StartTime AND current_time < EndTime echo Subject.
Something like this should work:
while($row = mysql_fetch_array($result)){
$startTime = strtotime($row['StartTime']);
$endTime = strtotime($row['StartTime']);
if (strtotime($current_time) > $startTime && strtotime($current_time) < $endTime
echo $row['Subject'];
}
putenv("TZ=Asia/Calcutta"); // To Set TimeZone
$now = date("Y-m-d H:i:s");
$sql = "select * from events where '$now' between StartTime and EndTime";
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);
}
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)