i have this function :
function get_user_dep($userid)
{
$sql = mysql_query("SELECT COUNT(userid) AS total_dep FROM `userdep` WHERE `type` LIKE 'Depozitare' AND DATE(`date`) <= NOW() AND DATE(`date`) >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
$row = mysql_fetch_array($sql);
$count = $row['total_dep'];
if ($count > 1) {
return 'Yes';
} else {
return 'No';
}
}
with database userdep
id/userid/type/date/amouth
i made with assoc, numrow , and it returns me No , and in the database i have more than 4 entrys in interval 7 days.
Sorry for having to ask this in an answer - my rep is too low. What field type is your date column? From what I just read in your comments on the answer below, the DATE field requires 'yyyy-mm-dd'.
1) SQL is valid.
2) Change this:
$row = mysql_fetch_array($sql);
to this:
$row = mysql_fetch_array($sql, MYSQL_ASSOC);
or to this:
$row = mysql_fetch_assoc($sql);
3) Also you can try this to check what you received back from DB.
echo print_r($row, true);
Related
I am trying to find the particular date data from database,
my concept is if 2018-11-30 is given to find in database if the date is present in database it should display the date in output, if not present it should add +1 date to 2018-11-30 and try to find the next date 2018-12-01 like wise it goes on.
but i am facing the problem the date is not checked in the database.i am not sure weather my code is correct or wrong can any one give me solution for it.
this is my code
$Firstdate = '2018-11-29';
$Lastdate = '2018-12-03';
$Sql2 = "SELECT ScheduleDate FROM `empdet`";
$result2 = mysqli_query($con, $Sql2);
while($row = mysqli_fetch_array($result2))
{
if($row["ScheduleDate"]==$Firstdate)
{
$DBfirstdate==$Firstdate;
echo "$DBfirstdatebb",$DBfirstdate;
break;
}
else {
$checkFDBdate=date('Y-m-d', strtotime("+1 day", strtotime($Firstdate)));
if($row["ScheduleDate"]==$checkFDBdate)
{
$DBfirstdate=$checkFDBdate;
echo "$DBfirstdate",$DBfirstdate;
break;
}
}
}
$Sql3 = "SELECT ScheduleDate FROM `empdet`";
$result3 = mysqli_query($con, $Sql3);
while($row = mysqli_fetch_array($result3))
{
if($row["ScheduleDate"] == $Lastdate) {
$DBlastdate==$Lastdate;
echo "$DBlastdateBB",$DBlastdate;
break;
}
else {
$checkLDBdate=date('Y-m-d', strtotime("-1 day", strtotime($Lastdate)));
if($row["ScheduleDate"]==$checkLDBdate)
{
$DBlastdate=$checkLDBdate;
echo "$DBlastdate",$DBlastdate;
break;
}
}
}
$sql ="select * from empdet where ScheduleDate between '".$DBfirstdate."' and '".$DBlastdate."'";
$result = $con->query($sql);
SELECT ScheduleDate FROM `empdet` where ScheduleDate > '$Firstdate' and ScheduleDate < '$Lastdate' order by ScheduleDate limit 1
Try this way. You will get the first raw from the date range given.
Select stuff from somewhere where something > 'value' order by something limit 1
I have a script written in PHP which reports sales activity.
FOLLOWING currently fetching just values. Today Yesterday Last 7 days.
Today for field use the following code:
if($x==0) {
$sql="SELECT SUM(incasat) FROM tichete WHERE DATE(datainchis) = DATE(NOW()) AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
Field yesterday to use the following code:
if($x==1) {
$sql="SELECT SUM(incasat) FROM tichete WHERE datainchis BETWEEN DATE_ADD(CURDATE(), INTERVAL -1 day) AND CURDATE() AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
I would like to do like this. I wish I could show collections on each and every day like Today Yesterday 3 days ago 3 days but for 3 days ago i want to see like yesterday not amount just pays from this day.
Enclose the code.
function get_user_incasari($x,$y)
{ // 0 - azi, 1 - ieri, 7 - ultimele 7 zile, 30 - luna asta, 31 - luna trecuta
if($x==0) {
$sql="SELECT SUM(incasat) FROM tichete WHERE DATE(datainchis) = DATE(NOW()) AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
if($x==1) {
$sql="SELECT SUM(incasat) FROM tichete WHERE datainchis BETWEEN DATE_ADD(CURDATE(), INTERVAL -1 day) AND CURDATE() AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
if($x==3) {
$sql="SELECT SUM(incasat) FROM tichete WHERE datainchis BETWEEN DATE_ADD(CURDATE(), INTERVAL -3 day) AND CURDATE() AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
if($x==7) {
$sql="SELECT SUM(incasat) FROM tichete WHERE datainchis BETWEEN DATE_ADD(CURDATE(), INTERVAL -7 day) AND CURDATE() AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
if($x==30) { //luna curenta
$sql="SELECT SUM(incasat) FROM tichete WHERE MONTH(datainchis) = MONTH(CURDATE()) AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
if($x==31) { //luna precedenta/trecuta
$sql="SELECT SUM(incasat) FROM tichete WHERE MONTH(datainchis) = MONTH(CURDATE() - INTERVAL 1 MONTH ) AND inchisde='$y'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!empty($row['SUM(incasat)'])) echo $row['SUM(incasat)']; else echo '0';
}
}
You can use timestamps (like your datainchis column), truncated to date, in GROUP BY queries. It's easy. For example, this gives you a summary, by day, starting eight days ago and ending yesterday. (Note: CURDATE() means DATE(NOW()).)
SELECT SUM(incasat) incasat_total, DATE(datainchis) datainchis
FROM tichete
WHERE inchisde='$y'
AND datainchis >= CURDATE() - INTERVAL 8 DAY
AND datainchis < CURDATE()
GROUP BY DATE(datainchis) WITH ROLLUP
Notice, please, that your code contains an error (a common error).
If you have timestamps and you say
datainichis BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE()
you get all the rows with timestamps starting with midnight yesterday, up to and including midnight today. You actually want to exclude midnight today; those records belong to today, not yesterday.
datainichis >= CURDATE() - INTERVAL 1 DAY
AND datainichis < CURDATE()
Notice the < in place of <=.
Your code also contains an inefficiency. The expression
DATE(datainichis) = CURDATE()
is not sargable. It defeats the use of an index on the datainichis column.
I have written a little essay on this topic, here.
I have table as seen below:
ID, Date, Type
1, 2015-1-1, 2
2, 2015-5-1, 5
3, 2015-8-10, 4
(before 2015-1-1 .... type = default
2015-1-1 <= Date < 2015-5-1 .... type = 2
2015-5-1 <= Date < 2015-8-10 .... type = 5
since 2015-8-10 .... type = 4)
I would like simply check which type is for any $date.
I tryed:
$sql = "SELECT * FROM smlouvy
WHERE Date < '".$date."'
ORDER BY Date LIMIT 1";
$result = MySQL_Query($sql);
if ( mysql_num_rows($result) == 0 ) {
$type = 'default';
}
else {
$row = mysql_fetch_array($result);
$type = $row["Type"];
}
You can try something like:
select ID,date,
case `date`
when `date`<='2015-11-01' then 4
when `date`>='2015-11-01' then 5
else 1 end as `type`
from tbl;
Note: This is just an example,you may need to modify the conditions as per your requirement.
Here is solution (if Date column matches within a certain range):
$dateFrom = '2015-5-1';
$dateTo = '2015-8-10';
// exemplary query
$query = "SELECT type FROM table_name
WHERE $dateFrom <= Date < $dateTo
ORDER BY Date ASC LIMIT 1 ";
// it will return the type of lower date column from range (type = 5)
My SQL query is selecting date and doing a count, as well as grouping by date.
I don't know how to output line by line JSON output.
$sql = "SELECT DATE(timestamp), COUNT(eventid)
FROM `tablex`
WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
GROUP BY DATE(timestamp) ";
$stream = mysqli_query($conn, $sql);
if (mysqli_num_rows($stream) > 0) {
while($row = mysqli_fetch_assoc($stream)) {
// Is this where I should echo JSON?
// The problem is I'm not retrieving records but count and doing
// a grouping
}}
Use mysqli_fetch_array(), also take the count with mysql_num_rows():
$sql = "SELECT DATE(timestamp), COUNT(eventid)
FROM `tablex`
WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
GROUP BY DATE(timestamp) ";
$stream = mysqli_query($conn, $sql);
if (mysqli_num_rows($stream) > 0) {
$rowCount = mysql_num_rows($result);
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
// Process JSON here use $row[0], $row[1], and so
}
}
Whatever you like to return as a JSON-string, you should always write your data into a single array, then use this nice little PHP-function called json_encode(). For example:
$sql = "SELECT
DATE(timestamp) as date_timestamp,
COUNT(eventid) as count_eventid
FROM `tablex`
WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
GROUP BY DATE(timestamp);";
$stream = mysqli_query($conn, $sql);
// prepare return array
$mydata = array(
'eventcount' => 0
);
if (mysqli_num_rows($stream) > 0) {
while($row = mysqli_fetch_assoc($stream)) {
// just collect your data here, do not JSONify here
$mydata['eventcount'] += $row['count_eventid'];
}
}
// We got all our data, so return JSON encoded array
echo json_encode($mydata);
You will get something like
{"eventcount":"1234"}
I managed to get an output:
$stream = mysqli_query($conn, $sql);
$lines = array();
while($line = mysqli_fetch_assoc($stream)) {
$llines[] = $line;
}
print json_encode($lines);
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);
}