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);
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);
}
I am trying to select the date in the field end_date that is less or equal to current date but did not work and my field end_date as the same date format(08-09-2014) data as current date below is my code thanks
$currentdate = date("d-m-Y");
$query1 = "SELECT * FROM location WHERE end_date <= '$currentdate'";
$result1 = mysql_query ($query1) or die('query error');
while( $line1 = mysql_fetch_assoc($result1)){
echo $line1['end_date'];
}
try this
SELECT * FROM location WHERE end_date <= DATE_FORMAT(CURDATE(), '%Y-%m-%d')
try with -
SELECT * FROM location WHERE end_date <= DATE_FORMAT(CURDATE(), '%d-%m-%Y')
$currentdate = date("Y-m-d");
$query1 = "SELECT * FROM location WHERE `end_date` <= '$currentdate'";
$result1 = mysql_query ($query1) or die('query error');
while( $line1 = mysql_fetch_assoc($result1)){
echo $line1['end_date'];
}
try this... must have in database date format;;
If your currentdate is independent of the system date (e.g. if you are operating over different timezones), and if, for some reason, your end_date is not a date type, then try this:
SELECT * FROM location
WHERE str_to_date(end_date, '%d-%m-%Y') <= str_to_date('$currentdate', '%d-%m-%Y')
where the format can be changed to match your inputs.
If you want to compare dates, then make sure you are comparing dates and not strings.
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 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);
}
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.