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)); ?>],
Related
I have all records in sequence from 1 onwards for each record displayed but wish to update each one with that sequence in a field within the table.
Any help?
if(isset($_POST['setorder']))
{
$i = 1;
//$today = date('Y-m-d', strtotime('-1 day'));
$routesql = $mysqli->query("SELECT * FROM routes WHERE status = 1");
while ($routerows = $routesql->fetch_array())
{
$rname = $routerows['routename'];
$routejobs = $mysqli->query("select tracking.*, district.* from tracking left join district on tracking.street = district.street
where tracking.date = '$today' AND tracking.status = 2 and route = '$rname' order by district.sortorder asc");
while ($routejrows = $routejobs->fetch_array())
{
echo $i.' - '.$routejrows['joborder'].' - '.$routejrows['addressto'];
echo '<br/>';
$i++;
}
}
}
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);
Im trying to merge or put an Array (called '$rows_ban') inside a sub item of another array (called '$rows') in a final array named '$rows_final'.
Im using array_merge but returns null inside 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[null]}
It should return the results in of the second query inside the 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[{...},{...},{...}]}
PHP Script:
$rows = array();
$rows_ban = array();
$rows_final= array();
$result1 = mysqli_query($link,"SELECT `id`,`sync_date`,`sync_time` FROM sync_log");
while($r = mysqli_fetch_array($result1)) {
$rows['date']= $r[2];
$rows['hour']= $r[3];
$rows['data'][]= null;
}
$result2 = mysqli_query($link,"SELECT cod, name, total from totals " );
while($r = mysqli_fetch_array($result2)) {
$rows_ban['cod'] = $r[0];
$rows_ban['name'] = $r[1];
$rows_ban['total'] = $r[2];
$result3 = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod=".$r[0]." order by dates desc");
while($r = mysqli_fetch_assoc($result3)) {
$rows_ban['sub_data'][] = $r;
}
$rows_final = array_merge($rows['data'],$rows_ban);
// here im trying to merge the $rows_ban array inside the
$rows['data']
}
echo json_encode($rows_final);
Not sure if that's what you wanted to accomplish since your description is very poor and hard to understand.
$output = [];
$tmpRows = [];
$result = mysqli_query($link, 'SELECT `id`,`sync_date`,`sync_time` FROM sync_log');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$output['date'] = $tmp[0]['sync_date'];
$output['time'] = $tmp[0]['sync_time'];
}
$result = mysqli_query($link, 'SELECT cod, name, total from totals ');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['cod'] = $tmp[0]['cod'];
$tmpRows['name'] = $tmp[0]['name'];
$tmpRows['total'] = $tmp[0]['total'];
$result = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod={$tmp[0]['cod']} order by dates desc");
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['sub_data'] = $tmp[0];
}
$output['data'] = $tmpRows;
}
print_r(json_encode($output));
Also array_merge doesn't work like you think it does. It returns merged array like it's name states. Regarding to your code, final result would be exactly $rows_ban encoded to json.
http://php.net/manual/en/function.array-merge.php
I have a table in mysql which has a startdate and enddate.
An example of 1 row would be:
startdate -> 20121224
endate -> 20121226
title -> name
this would return (OUTPUT!!!):
[{"user":"378","date":"UNIX_TIMESTAMP(startdate)","title":"name","description":"6 Days","url":"UNIX_TIMESTAMP(enddate)","bmanager":"manager name","academic_year":"20120801","division":"division name","manager_id":"3"}]
As this record spans over 3 days i would like the JSON to output one for each date (the only differnce being the date, please see below) I WANT THIS INSTEAD
[{"user":"378","date":"UNIX_TIMESTAMP(1st date)","title":"name","description":"6 Days","url":"UNIX_TIMESTAMP(1st date)","bmanager":"manager name","academic_year":"20120801","division":"division name","manager_id":"3"},
{"user":"378","date":"UNIX_TIMESTAMP(2nd date)","title":"name","description":"6 Days","url":"UNIX_TIMESTAMP(2nd date)","bmanager":"manager name","academic_year":"20120801","division":"division name","manager_id":"3"},
{"user":"378","date":"UNIX_TIMESTAMP(3rd date)","title":"name","description":"6 Days","url":"UNIX_TIMESTAMP(3rd date)","bmanager":"manager name","academic_year":"20120801","division":"division name","manager_id":"3"},]
THIS IS THE SCRIPT IM USING:
$sqldata = mysql_query('
SELECT
datediff(requests.end_date, requests.start_date) as numdays,
requests.user,
UNIX_TIMESTAMP(requests.start_date) AS date,
requests.employee AS title,
requests.days AS description,
UNIX_TIMESTAMP(requests.end_date) AS url,
business.line_manager AS bmanager,
requests.academic_year,
business.academic_year,
business.division,
line_managers.userid AS manager_id
FROM requests
INNER JOIN holiday_entitlement_business_manual AS business ON requests.user=business.userid AND requests.academic_year=business.academic_year
INNER JOIN line_managers ON business.line_manager=line_managers.name
WHERE requests.approved = 1
');
$posts = array();
while($row = mysql_fetch_assoc($sqldata))
{
$row['date'] = $row['date'].'000';
$row['url'] = $row['url'].'000';
$posts[] = $row;
}
mysql_free_result($sqldata);
die(json_encode($posts));
Try to replace your code by the following:
$sqldata = mysql_query('
SELECT
requests.start_date as startdate,
datediff(requests.end_date, requests.start_date) as numdays,
requests.user,
UNIX_TIMESTAMP(requests.start_date) AS date,
requests.employee AS title,
requests.days AS description,
UNIX_TIMESTAMP(requests.end_date) AS url,
business.line_manager AS bmanager,
requests.academic_year,
business.academic_year,
business.division,
line_managers.userid AS manager_id
FROM requests
INNER JOIN holiday_entitlement_business_manual AS business ON requests.user=business.userid AND requests.academic_year=business.academic_year
INNER JOIN line_managers ON business.line_manager=line_managers.name
WHERE requests.approved = 1
');
$posts = array();
while($row = mysql_fetch_assoc($sqldata))
{
$startDate = $row['startdate'];
unset($array['startdate']);
$dayDiff = $row['numdays'];
$row['date'] = $row['date'].'000';
$row['url'] = $row['url'].'000';
for($i = 0; $i <= $dayDiff; $i++)
{
$row['date'] = ...; // Do here the date parsing and add $i to the days
$posts[] = $row;
}
}
mysql_free_result($sqldata);
die(json_encode($posts));
These functions dateparse() and mktime() will probably help you with the date manipulation.
Not sure whether I got your point. This could give you a starting point.
Basically, you need to fetch all rows, and then create one record for every day you wish to take into account.
$sqldata = mysql_query('
SELECT
datediff(requests.end_date, requests.start_date) as numdays,
requests.user,
UNIX_TIMESTAMP(requests.start_date) AS date,
requests.employee AS title,
requests.days AS description,
UNIX_TIMESTAMP(requests.end_date) AS url,
business.line_manager AS bmanager,
requests.academic_year,
business.academic_year,
business.division,
line_managers.userid AS manager_id
FROM requests
INNER JOIN holiday_entitlement_business_manual AS business ON requests.user=business.userid AND requests.academic_year=business.academic_year
INNER JOIN line_managers ON business.line_manager=line_managers.name
WHERE requests.approved = 1
');
$posts = array();
while($row = mysql_fetch_assoc($sqldata))
{
$row['date'] = $row['date'];
$row['url'] = $row['url'];
for($x = $row['date']; $x < $row['url']; $x+= 86400) {
// where 86400 makes you advancing by a day in secs
$row['date'] = $x;
$row['url'] = $x;
$posts[] = $row;
}
$posts[] = $row;
}
mysql_free_result($sqldata);
die(json_encode($posts));
I have the following tables in my DB:
id
title
heading
content
date
tags
username
like
dislike
comments
I have the database hooked up so that it will show what's in the rows, but I don't know how to make it so that it will generate and list a "post block" every time a new entry is made. I would also like to list them from newest posts to oldest, all while limiting the posts to 10-20 per page.
<?php
$connect = mysql_connect('localhost','root','','andrewryan') or die('error connection');
mysql_select_db('andrewryan');
$query = "Select * FROM entry";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$username = $row['username'];
$title = $row['title'];
$heading = $row['heading'];
$content = $row['content'];
$tags = $row['tags'];
$like = $row['like'];
$dislike = $row['dislike'];
$comment = $row['comment'];
$date = $row['date'];
?>
I also have another page with just one block of html. Which is the post framework with all the variables given where they are needed. Any reference for what I'm going for can be found at this link if it helps: HERE
As far as the query:
// Tildes on date since it is a keyword and some databases will error out without them
// Order by date is if you are using a compatible storing: unix timestamp or DateTime field
$query = "Select * FROM entry ORDER BY `date` DESC";
$result = mysql_query($query);
$rowCount = 0;
while($row = mysql_fetch_array($result)) {
$username[$rowCount] = $row['username'];
$title[$rowCount] = $row['title'];
$heading[$rowCount] = $row['heading'];
$content[$rowCount] = $row['content'];
$tags[$rowCount] = $row['tags'];
$like[$rowCount] = $row['like'];
$dislike[$rowCount] = $row['dislike'];
$comment[$rowCount] = $row['comment'];
$date[$rowCount] = $row['date'];
$rowCount++;
}
This is as far as showing the posts:
// limit is used to show the max posts per page.
$limit = 20;
//The following for is for paging
for($i = 1; $i <= $numofpages; $i++){
if($i == $page){
echo $i . " ";
}else{
echo "<a href='page.php?page=" . $i . "'>" . $i . "</a> ";
}
}
// The following is to show your post blocks
for($j = 0; $j < $limit; $j++){
//This will give you the appropriate post for the page
$temp = $j + (($page * $limit) - $limit);
// Your code to show your post blocks
echo $username[$temp]; //For example, just format for your site layout.
}
SELECT all the fields that you are interested to fetch.
Use DATE_FORMAT function to format the date field and assign to a new alias.I named it ndate.
Then ORDER BY ndate
SELECT username,title,heading,content,tags,like,dislike,comment,DATE_FORMAT(date, '%d-%M-%Y') AS ndate FROM entry ORDER BY ndate
fetch the date as $row['ndate']