Google charts column graph from MySql database - php

The real question is how do I populate a Google charts datatable form a MySql query when a date is used for the first column?
I am trying to create a column chart using the Google Charts API. The problem is that the data is time series data. There are many dates represented. The way that this is done to create the data table is to assign column 0 to the date and each subsequent column represents the data being measured. That information is derived from the documentation. I just can't figure out how to get the data to assign to the subsequent columns. I have researched this extensively now and there are some answers that are close, but I can't make them work for this. Here is the code that is currently generating my chart data table:
$invArr = array('cols' => array(
array('label' => 'date', 'type' => 'date'),
array('label' => 'SKU', 'type' => 'number')),
'rows' => array());
while($row = mysql_fetch_row($query)) {
$invArr['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
I understand from the Google charts documentation that column 0 is always the date for continuous data. Each subsequent column is the data that is being measured, in this case ths SKU numbers. I need to have the first array in each row represent the date and the subsequent arrays represent the qtyoh data. I don't know how to do that.

I researched this for several days and I was finally able to solve the problem by piecing together answers to many different questions.
I started by querying the distinct dates and placing them into an array. The way this is done is very important because the date is a string when json encoded. It is important to parse it out and pass it in the Date(year,month,day) format exactly. It is also important that later on you use a variable to represent the date.
$dateArray = array();
while($row = mysql_fetch_row($queryDates)) {
$dtArray = explode('-',$row[0]);
$day = (int) $dtArray[1];
$month = ((int) $dtArray[0])-1;
$year = (int) $dtArray[2];
$dateArray[] = "Date($year, $month, $day)";
}
I then set up the columns for the table by looping through a query of the SKU's.
$invArr = array(
'cols' => array(
array('label' => 'Date', 'type' => 'date')
)
);
while($row = mysql_fetch_row($querySkus)) {
$invArr['cols'][] = array('label' => $row[0], 'type' => 'number');
}
I then query the quantities and place them into an array. I then loop through each value and populate the table array ($inVarr).
$quantities = array();
while($row = mysql_fetch_row($queryQty)) {
$quantities[] = (int) $row[0];
}
$qtyCounter = 0;
for($i=0;$i<count($dateArray);$i++) {
$invArr['rows'][] = array(
'c' => array(
array('v' => $dateArray[$i]),
array('v' => $quantities[$qtyCounter]),
array('v' => $quantities[$qtyCounter+1]),
array('v' => $quantities[$qtyCounter+2])
)
);
$qtyCounter=$qtyCounter+3;
}
I can then just echo the json encoded array which will return the data for the data table.
echo json_encode($invArr);
I believe that this is a bit clunky, but it works.

Related

Using a php foreach loop with ALTER TABLE mysql to update multiple column names

My first post on stack after all these years of learning :) So much to thank this community. But anyway...
I'm trying to add new column names to a database dynamically based on what my array will hold. The array's data is unknown/can change, otherwise I'd set it all manually in mysql.
So far, I can get the ALTER TABLE to add a single column entry with this code, but I can't get the foreach loop to iterate through the array for the others following. Surely you can do this I presume?
$test_prod = [
['name' => 'sunny', 'was' => 111, 'now' => 222,],
['name' => 'moon', 'was' => 333, 'now' => 444,],
['name' => 'eclipse', 'was' => 555, 'now' => 666,]
];
foreach ($test_prod as $v) {
$t = $v['name'];
$column_name = $conn->real_escape_string($t);
$update = mysqli_query($conn, "ALTER TABLE table ADD $column_name VARCHAR(255)") or die(mysql_error());
return $update;
}

PHP & sqlsrv - create array from results, without knowing column names?

Using the below, I echo a JSON array of the results. But this requires that I identify the column names which I'd like to return from the SQL query:
$new_sql = "SELECT TOP 200 * FROM STracker ORDER BY [ID] DESC";
$check_statement = sqlsrv_query($conn, $new_sql);
$data = array();
while($row = sqlsrv_fetch_array($check_statement, SQLSRV_FETCH_ASSOC)) {
$data['data'][] = array(
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
);
}
Is there any way to create that array information, but return all of the columns returned by the query dynamically? So by using SELECT * FROM, all of the column data is returned in the array but without me needing to write out all of these individually? (the below)
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
Ok I forgot to add that I'd tried this:
$data['data'][] = array($row);
Which is clearly wrong, and after using the following, it works perfectly!
$data['data'][] = $row;

PHP error when using date_diff() function within DataTables $columns array

Forgive me, this is a long one. I want to give all the background for this question.
I am using DataTables server-side processing for a project. My goal is to utilize the echo function to echo the number of days between today's date and dates in a column of my database called CreatedDate, which is a DateTime type.
I was trying to get the basic functionality working outside of DataTables first, and the function below works as intended, and outputs an $current_date of the number of days between $date and $date as: "16 days live", "15 days live", etc.:
$sql = "SELECT CreatedDate FROM Estimates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$created_date = $row["CreatedDate"];
$date = new DateTime($created_date);
$current_date = new DateTime();
$diff = date_diff($date, $current_date);
echo $diff->format('%d days live');
}
} else {
echo "No results";
}
In my DataTables $columns array, I am trying to achieve the same effect:
// date variable
$created_date = 'CreatedDate';
$current_date = new DateTime();
// array of database columns which should be read and sent back to DataTables.
// the 'db' parameter represents the column name in the database, while the 'dt'
// parameter represents the DataTables column identifier.
$columns = array(
array( 'db' => 'Client', 'dt' => 0 ),
array( 'db' => 'EstimateNumber', 'dt' => 1 ),
array( 'db' => 'Status', 'dt' => 2 ),
array( 'db' => 'CurrentEstimateTotal', 'dt' => 3 ),
array(
'db' => $created_date,
'dt' => 4,
'formatter' =>
function ($created_date, $row) use ($current_date) {
$date = new DateTime($created_date);
$diff = date_diff($date, $current_date);
echo $diff->format('%d days live');
}
)
);
I keep recieving an error of:
PHP Notice: Trying to get property of non-object.
How can I fix this? I am having a hard time getting a var_dump() of the $created_date and $date variables within the DataTables array to see what the problem is.
For more information about DataTables server-side processing, I am using this template as a base for my DataTables script. The DataTables script also uses this helper class. Thank you in advance!
Just return your string from callback.
'formatter' =>
function ($created_date, $row) use ($current_date) {
$date = new DateTime($created_date);
$diff = date_diff($date, $current_date);
return $diff->format('%d days live'); //That will solve your problem
}

Cakephp get all months records with a single query i.e with single find

I am working on a ecommerce with platform cakephp and using google charts for reports.My requirement is to get all records as per all 12 months, so I have used following code for a single month
Query
SELECT COUNT(*) AS count FROM orderproductmasters AS Orderproductmaster
LEFT JOIN ordermasters AS Ordermaster ON
(Orderproductmaster.ordermaster_id = Ordermaster.id) LEFT JOIN productmasters AS Productmaster ON
(Orderproductmaster.productmaster_id = Productmaster.id)
WHERE Ordermaster.orderstatusmaster_id = 1 AND Month(Orderproductmaster.created) = 8
Code
$this->Orderproductmaster->find('count',
array('conditions'=>array('Ordermaster.orderstatusmaster_id'=>1,'
Month(Orderproductmaster.created)'=>8)));
Since, I need records as per Jan, feb,march and all 12 months...,so for 12 months I am using following code
for($i=1;$i<13;$i++)
{
$orderproductmasters[$i] = $this->Orderproductmaster->find('count',
array('conditions'=>array('Ordermaster.orderstatusmaster_id'=>1,
'Month(Orderproductmaster.created)'=>$i)));
}
So question might be silly, but is it possible to get all months record without using for loop i.e, within a single query.
Thanks in advance
I think , your need can be fulfilled by using cursors in stored procedure. And then using stored procedure to cake-php.
Example on db side is here
$options = array();
$options['fields'] = array('COUNT(Orderproductmaster.id)');
$options['conditions'] = array('Ordermaster.orderstatusmaster_id = 1',
'Month(Orderproductmaster.created) BETWEEN 1 AND 12');
$options['joins'] = array(
array(
'table' => 'ordermasters',
'alias' => 'Ordermaster',
'type' => 'left',
'conditions' => array(
'Orderproductmaster.ordermaster_id = Ordermaster.id'
)
),
array(
'table' => 'productmasters',
'alias' => 'Productmaster',
'type' => 'left',
'conditions' => array(
'Orderproductmaster.productmaster_id = Productmaster.id'
)
)
);
$options['group'] => array('Month(Orderproductmaster.created)');
$this->Orderproductmaster->find('all',$options);
What About something like:
$this->Orderproductmaster->find('count',
array(
'fields'=>'DISTINCT(Month(Orderproductmaster.created)),
'conditions'=>array('Ordermaster.orderstatusmaster_id'=>1,'
Month(Orderproductmaster.created)'=>8)));

Create PieChart with google chart api and php

I'm kinda new to google chart api, and still wiping the dust out my php knowledge, so maybe someone can help with this (IMO) basic question...
So I have this php class wich queries data from server and should post it back to my page. There is a working Line Chart in it, as you can see at the snippet below:
$rowdata = array();
$i=0;
$_POST['from'] = str_replace("/","-",$_POST['from']);
$_POST['to'] = str_replace("/","-",$_POST['to']);
$cur_date = $_POST['from'];
$sql = "SELECT DATE(entered),
COUNT(*) AS totalaccounts,
SUM(CASE WHEN facebook_username != '' THEN 1 ELSE 0 END) AS facebook,
SUM(CASE WHEN facebook_username = '' THEN 1 ELSE 0 END) AS standard
FROM Account
WHERE entered BETWEEN '". $_POST['from'] ."' AND '". $_POST['to'] ."'
GROUP BY DATE(entered)";
$result = $dbMain->query($sql);
$rows = tratarDadosParaGrafico($result);
$return = json_encode(array('cols' => $cols, 'rows' => $rows));
$data = array(
'cols' => array(
array('id' => '', 'label' => 'Date', 'type' => 'string'),
array('id' => '', 'label' => 'Total Accounts', 'type' => 'number'),
array('id' => '', 'label' => 'Total Accounts (Facebook)', 'type' => 'number'),
array('id' => '', 'label' => 'Total Accounts (Non Facebook)', 'type' => 'number')
),
'rows' => $rows
);
$chart = new Chart('LineChart');
$options = array('title' => 'Accounts');
$chart->load(json_encode($data));
echo $chart->draw('rchart', $options);
What I was trying to do was use the same query result ($data) to populate another chart, this one a pie chart... So I simply pasted the last 4 lines of code, changing the parameter when creating a new instance of Chart:
$chart = new Chart('PieChart');
$options = array('title' => 'Accounts');
$chart->load(json_encode($data));
echo $chart->draw('pchart', $options);
After this, I close the php tag and use 2 divs to show my charts...
<div id="rchart"></div>
<div id="pchart"></div>
Everything here comes from this index.php class, I haven't seen html files at all... What happens is I can see the pie chart right below the line chart, but it comes with no data within, i.e., the whole chart is grey and labeled as "Other"
What may I've done wrong? Thanks in advance!
[EDIT]
Let's say I want a Pie Chart with only 2 slices, why the code below doesn't works? (I get "Cannot read property '1' of undefined" error)
$data = array(
'cols' => array(
array('label' => 'Pie slice labels', 'type' => 'string'),
array('label' => 'Pie slice values', 'type' => 'number')
),
'rows' => array(
array('v' => intval($facebook_accounts[0]), 'type' => 'int'),
array('v' => intval($default_accounts[0]), 'type' => 'int')
)
);
$chart = new Chart('PieChart');
$options = array('title' => 'Accounts');
$chart->load(json_encode($data));
echo $chart->draw('piechart', $options);
[EDIT] Maybe this can help you helping me :)
https://groups.google.com/forum/#!topic/google-visualization-api/Wi_WOVOgzG8
Creating Pie char from mysql database using php and google charts
PieCharts don't use the same data structure as the LineCharts. PieCharts expect two columns of data: the first is the pie slice labels, and the second is the pie slice values. You will have to reconfigure your data pull to put the data in the correct format.
Edit:
Here's some sample PHP pseudo-code for building a DataTable for a PieChart:
$data = array(
'cols' => array(
array('label': 'Pie slice labels', type: 'string'),
array('label': 'Pie slice values', type: 'number')
),
'rows' => array()
);
while (/* loop over SQL results */) {
$data['rows'][] = array('c' => array(
array('v' => /* pie slice label */),
array('v' => /* pie slice value */) // use (int) or (float) to parse appropriately, as many databases output numbers as strings
));
}

Categories