I've tried to make this work for 24 hours now, and now it feels like I'm close to it!
I would like to get date (column:datum) and location (column:plats) from MySQL, where my code looks like:
<?php
$sql = "SELECT datum FROM gigs GROUP BY DATE_FORMAT( datum, '%Y' ) ORDER BY datum DESC";
$result = mysql_query($sql);
while($r = mysql_fetch_array($result)) {
$date = $r['datum'];
$date_new = new DateTime($date);
$year = $date_new->format('Y');
$month = $date_new->format('M');
$day = $date_new->format('d');
$sql2 = "SELECT * FROM gigs WHERE DATE_FORMAT( datum, '%Y' ) = $year ORDER BY datum ASC";
$result2 = mysql_query($sql2);
echo "<tr height=20px><td></td><td align=center><b>".$year."</b></td></tr>";
echo "<tr><td><b>".$month."</b></td></tr>";
while($r2 = mysql_fetch_array($result2)) {
$date2 = $r2['datum'];
$date_new2 = new DateTime($date2);
$year2 = $date_new2->format('Y');
$month2 = $date_new2->format('M');
$day2 = $date_new2->format('j');
//echo "<b>Month: ".$month."</b>";
//echo "<b>Month2: ".$month2."</b>";
if($month != $month2) {
echo "<tr><td> </td></tr><tr><td><b>".$month2."</b></td></tr>";
}
$month = $month2;
echo "<tr class=giglist><td>".$day2."</td><td>".$r2['plats']."</td></tr>";
}
echo "</td></tr>";
}
?>
This gives me:
2011
Jan
1. Location
2. Location
3. Location
...
Feb
1. Location
2. Location
3. Location
...
...
Dec
1. Location
2. Location
3. Location
...
2010
Dec
Jan
1. Location
2. Location
3. Location
...
Feb
1. Location
2. Location
3. Location
...
...
Dec
1. Location
2. Location
3. Location
...
I do NOT want the extra December written under "2010"...
I hope someone can help, cause I'm lost in my own code xD thanks!
Your code is to much complicated, you can do that with only one query, see this code
<?php
$sql = 'SELECT
*,
DATE_FORMAT( datum, "%Y" ) "year",
DATE_FORMAT( datum, "%M" ) "month",
DATE_FORMAT( datum, "%e" ) "day"
FROM gigs
ORDER BY year DESC, month DESC, day ASC';
$year = null;
$month = null;
$stmt = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
if ($year != $result['year']) {
// Year changed
$year = $result['year'];
echo "<tr height=20px><td></td><td align=center><b>".$year."</b></td></tr>";
}
if ($month != $result['month']) {
// Month changed
$month = $result['month'];
echo "<tr><td> </td></tr><tr><td><b>".$month."</b></td></tr>";
}
echo "<tr class=giglist><td>".$result['day']."</td><td>".$row['plats']."</td></tr>";
}
First of all, please please, I really recommend you to use the separation of concerns principle! Use a templating system, e.g. Smarty, http://www.smarty.net/ and use a database abstraction layer. Then your code will be MUCH more flexible, easier to read, etc. and then you wouldn't need to ask this question, and save lots and lots of time.
This said, you could try this (I didn't test it though..);
<?php
$sql = "SELECT datum FROM gigs GROUP BY DATE_FORMAT( datum, '%Y' ) ORDER BY datum DESC";
$result = mysql_query($sql);
while($r = mysql_fetch_array($result))
{
$date = $r['datum'];
$date_new = new DateTime($date);
$year = $date_new->format('Y');
$month = $date_new->format('M');
$day = $date_new->format('d');
$sql2 = "SELECT * FROM gigs WHERE DATE_FORMAT( datum, '%Y' ) = $year ORDER BY datum ASC";
$result2 = mysql_query($sql2);
echo "<tr height=20px><td></td><td align=center><b>".$year."</b></td></tr>";
$first_month_printed = false;
while($r2 = mysql_fetch_array($result2))
{
$date2 = $r2['datum'];
$date_new2 = new DateTime($date2);
$year2 = $date_new2->format('Y');
$month2 = $date_new2->format('M');
$day2 = $date_new2->format('j');
if($month != $month2) {
echo "<tr><td> </td></tr><tr><td><b>".$month2."</b></td></tr>";
} else if (!$first_month_printed)
echo "<tr><td> </td></tr><tr><td><b>".$month2."</b></td></tr>";
$first_month_printed = true;
}
$month = $month2;
echo "<tr class=giglist><td>".$day2."</td><td>".$r2['plats']."</td></tr>";
}
echo "</td></tr>";
}
?>
Related
I am trying to create an array in $data, but it is not happening. I am using this code to make a day wise sale chart.
$data = array();
for ($i = 0; $i <= 10; $i++) {
$billdate = date('d-m-Y', strtotime("-$i day"));
$sqlQuery = "select sum(amount),bill_date from msr_bills WHERE bill_date='$billdate' ";
$result = mysqli_query($con, $sqlQuery);
$fetchamount = mysqli_fetch_row($result);
$sum = $fetchamount[0];
$data = new \stdClass();
$data->bill_date = $billdate;
$data->amount = $sum;
$report_JSON = json_encode($data);
echo $report_JSON.",";
}
You can merge your loop into one query, and then iterate over the results instead:
$data = array();
$billdate = date('Y-m-d', strtotime('-10 day'));
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE bill_date >= '$billdate'
GROUP BY bill_date";
$result = mysqli_query($sqlQuery);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = (object)$row;
}
$report_JSON = json_encode($data);
echo $report_JSON;
}
Note that your date format is not compatible with MySQL dates, which are stored in Y-m-d format, and I have changed that in the code. If your bill_date column is actually a text field stored in d-m-Y format, you will need to convert it in the query like so:
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE STR_TO_DATE(bill_date, '%d-%m-%Y') >= '$billdate'
GROUP BY bill_date";
Note also that you can in fact do the computation of $billdate internal to your SQL query using date arithmetic:
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE STR_TO_DATE(bill_date, '%d-%m-%Y') >= CURDATE() - INTERVAL 10 DAY
GROUP BY bill_date";
And if you are running MySQL 8.0+, you can do the entire operation in MySQL:
$sqlQuery = "SELECT JSON_ARRAYAGG(data) AS data
FROM (SELECT JSON_OBJECT('bill_date', bill_date, 'amount', SUM(amount)) AS data
FROM msr_bills
WHERE bill_date >= CURDATE() - INTERVAL 10 DAY
GROUP BY bill_date) d";
$result = mysqli_query($sqlQuery);
if ($result) {
$row = mysqli_fetch_assoc($result);
$report_JSON = $row['data'];
echo $report_JSON;
}
Demo on dbfiddle
Put your echo outside loop. remove code $report_JSON = json_encode($data);
$respnseArr = array();
{
.
.
.
$respnseArr[] = $data;
}
echo json_encode($respnseArr);
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'm trying to create a graph like this http://jsfiddle.net/9mmrbjt7/1/
I have a script created that will add the data to the graph. The date and the value is stored in db and it works just fine.
The php script counts the number of dates and uses it as a value and assign it to the date.
The problem is if someone miss one day it skips the value which I understand.
So how can I assign value zero to skipped day?
2014-07-23
2014-07-23 = 2,
2014-07-24 -> wasn't submitted so the 0 should be added to the graph with the date.
2014-07-25
2014-07-25
2014-07-25= 3,
php script
$user_curr_id = $_SESSION['user_id'];
$sql = mysqli_query($con,"SELECT * FROM rosary WHERE user_ids = $user_curr_id ORDER BY datum ASC");
$array1 = array();
while($row = mysqli_fetch_array($sql)){
$array1[] = '"' . $row['datum'] . '"';
}
$tags = implode(', ', array_unique(array_map('trim',explode(',',implode(',',$array1)))));
$sql = mysqli_query($con,"SELECT datum, COUNT(datum) cnt
FROM rosary
WHERE user_ids = $user_curr_id
GROUP BY datum;");
$result = array();
while ($row = mysqli_fetch_array($sql)) {
$result[] = $row['cnt']; // add the content of field cnt
}
in js script
labels : ["Start",<?php echo $tags; ?>] -> list the dates from db
data : [0,<?php echo implode(',', $result); ?>]-> list values from db
php:
$sql = mysqli_query($con,"SELECT datum, COUNT(datum) as cnt
FROM rosary
GROUP BY datum
ORDER BY datum ASC;");
$result = array();
$start = null;
$end = null;
while ($row = mysqli_fetch_array($sql)) {
$result['"'.$row['datum'].'"'] = $row['cnt'];
if(is_null($start)) $start = $row['datum'];
$end = $row['datum'];
}
$res_array = array();
if(!is_null($start)){
$i = strtotime($start);
while($i <= strtotime($end)){
$res_array['"'.date('Y-m-d',$i).'"'] = 0;
$i = strtotime("+1 day",$i);
}
}
foreach($result as $date => $val){
$res_array[$date] = $val;
}
in js script
labels : ["Start",<?php echo implode(',',array_keys($res_array)) ?>],
data : [0,<?php echo implode(',', array_values($res_array)); ?>],
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
Why is it that when I view the month of November 2010 it also views the month of 2009? Can anyone help me?
<?php include("db.php");
$query = mysql_query("SELECT distinct YEAR(local_date) as year FROM tbl_localnews order by local_date desc");
while ($row = mysql_fetch_array($query)) {
//$row = array_unique($r);
$unique_year = $row['year'];
echo($unique_year)."<br>";
$query2 = mysql_query("select distinct monthname(local_date) as month from tbl_localnews where local_date like '$unique_year%' order by local_date desc");
while ($r2 = mysql_fetch_array($query2)) {
//$row2 = array_unique($r2);
$unique_month = $r2['month'];
print("<a href='news.php?month=$unique_month'&year=$unique_year>News for $unique_month</a><br>");
//echo($unique_month);
}
}
?>
This is my display
<?php
$year = $_REQUEST['year'];
$last_date = "";
$result = mysql_query("SELECT *,YEAR(local_date) as year FROM tbl_localnews where year(local_date)='".$year."' ORDER BY local_date DESC ");
//echo '<h1>'.$month.'</h1>';
if (mysql_num_rows($result)) {
while ($row = mysql_fetch_array($result)) {
if ($row['local_date'] != $last_date) {
print("<h2>News for ".date('F j, Y', strtotime($row['local_date']))."</h2>");
$last_date = $row['local_date'];
}
print("<p><b>".$row['local_title']."</b></p>");
print("<p>".$row['local_desc']."</p>");
// print("<p><b>".date('F j, Y',strtotime($row['local_date']))."</b></p>");
//print("<p><b>".$row['local_title']."</b></p>");
//print("<p>".$row['local_desc']."</p>");
}
mysql_free_result($result);
}
?>
I take it that you're seeing something like
2010<br><a href='news.php?month=November&year=2010'>News for November</a><br>
2009<br><a href='news.php?month=September&year=2009'>News for September</a><br>
in the output of your first example? This is because you're looping through each year and for each year, you're retrieving the months:
$query = mysql_query("SELECT distinct YEAR(local_date) as year FROM tbl_localnews order by local_date desc");
while($row = mysql_fetch_array($query)) { // loop through each year
$unique_year = $row['year'];
echo($unique_year)."<br>";
/* get the months for current year */
$query2 = mysql_query("select distinct monthname(local_date) as month from tbl_localnews where local_date like '$unique_year%' order by local_date desc");
while($r2 = mysql_fetch_array($query2)) { // loop through each month for the current year
$unique_month = $r2['month'];
print("<a href='news.php?month=$unique_month'&year=$unique_year>News for $unique_month</a><br>");
}
}
if you have 2 records with unique year values in your tbl_localnews table you're going to end up with 2 lines in your output. If you just want 1 record, append LIMIT 1 to the end of your query.
I managed to get the following to work for your display page:
<?php
include("db.php");
$year = $_REQUEST['year'];
$month = $_REQUEST['month'];
$last_date = "";
$result = mysql_query("SELECT *, YEAR(local_date) as year FROM tbl_localnews where YEAR(local_date)=".$year." AND monthname(local_date) = '".$month."' ORDER BY local_date DESC ");
if (mysql_num_rows($result) != 0) {
while ($row = mysql_fetch_array($result)) {
if ($row['local_date'] != $last_date) {
print("<h2>News for ".date('F j, Y', strtotime($row['local_date']))."</h2>");
$last_date = $row['local_date'];
}
print("<p><b>".$row['local_title']."</b></p>");
print("<p>".$row['local_desc']."</p>");
}
}
mysql_free_result($result);
?>