I already have checked similar answer. But i have different issue here!
TO create googlce char I am creating json string by fetching data from table.
Table has only two rows.
Here is how the json string is constructed:
$result = $mysqli->query('SELECT * FROM view_name');
$p= $mysqli->query('SELECT Index_val FROM view_name where ind_type=pcount');
//echo "$p";
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'pcount', 'type' => 'string'),
array('label' => 'ncount', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) $r['ind_type']);
$temp[] = array('v' => (int) $r['Index_val']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
Here only two values I need to fetch from database pcount and ncount. I dont want to use above procedeure.
What I want is to fetch the values of pcount and ncount from table manually, store in variable and construct the json string.
Like this :
$p= $mysqli->query('SELECT Index_val FROM view_name where ind_type=pcount'); // Please correct if wrong
same way get get ncount.
Now how can I create above json string from this?
Resulting string will be like this:
{
"cols":[
{"label":"pcount","type":"string"},
{"label":"ncount","type":"number"}],
"rows":[
{"c":
[
{"v":"pcount"},
{"v":179} // 179 is pcount
]
},
{"c":
[
{"v":"ncount"},
{"v":285} //285 is ncount
]
}
]
}
Related
What I'm trying to do is preserve the order of an array, while determining if each of the numbers match numbers that were pulled from the database. What I have is an array of numbers ($ids), and a non empty array of rows ($rows)
$images = array();
$ids = array(
0 => '41',
1 => '42',
2 => '43',
3 => '44'
);
// database example
$rows = array(
0 => array(
'name' => 'John Doe',
'id' => '42'
),
1 => array(
'name' => 'Jane Doe',
'id' => '43'
),
);
$i = 0;
foreach ($rows as $row) {
// This works, but it doesn't preserve the order of the $ids array
if (in_array($row['id'], $ids[$i])) {
// add $id to a new array
// or use the same $id array
$images[$i]['name'] = $row['name'];
$images[$i]['id'] = $row['id'];
$i++;
}
}
Any help would be appreciated.
Since id is unique in the rows from your database, you can index the $rows array by id to make it easier to look up values there. You can do this with array_column like this:
$rows = array_column($rows, null, 'id');
Or add them to $rows using id as index as you fetch them from the db like this:
while ($row = //whatever query result/prepared statement fetch you're using) {
$rows[$row['id']] = $row;
}
Then, instead of iterating $rows, you can iterate $ids. This will ensure that the resulting $images array will be in the same order as $ids.
foreach ($ids as $id) {
if (isset($rows[$id])) {
$images[] = [
'name' => $rows[$id]['name'],
'id' => $rows[$id]['id']
];
}
}
Another thing that might make this easier (unless you're using the non-matching rows for something else), would be to use the $ids array as a parameter to a WHERE id IN clause in the query that's selecting $rows, so you won't have to do that filtering in PHP. Here's a Q&A that shows how to do that with PDO, for example: PHP - Using PDO with IN clause array.
You could iterate over ids array instead. It will be something like this:
foreach($ids as $id) {
$data = find($id, $rows);
if ($data === null) {
continue;
}
$images[] = [
'name' => $data['name'],
'id' => $data['id']
];
}
function find($id, $rows) {
foreach($rows as $row) {
if($row['id'] == $id) {
return $row;
}
}
return null;
}
Totally agree with #Don't Panic, you should fetch only the data you'll use if possible.
I'm trying to create Google Timeline chart using PHP & MySQL but without any success so far. So after endless hours of trying I've manage this so far:
First, I tried to create json using PHP (I believe that I've missed something here)
PHP
try {
$db = connectPDO();
$result = $db->query("SELECT naziv_plan AS name,
objava_odluke AS start_date,
datum_stupanja_glasnika AS end_date
FROM ispu_plan
WHERE datum_donosenja_plana
BETWEEN '2014-01-01'
AND CURDATE()
ORDER BY datum_donosenja_plana ASC");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Godina', 'type' => 'string'),
array('label' => 'Odluka', 'type' => 'number'),
array('label' => 'glasnik', 'type' => 'number')
);
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) $r['naziv_plan']);
$temp[] = array('v' => (int) $r['objava_odluke']);
$temp[] = array('v' => (int) $r['datum_stupanja_glasnika']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table,JSON_NUMERIC_CHECK);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Using this block of code, I get this JSON (and it's valid, checked with JSONLint) But, I detected some unusual formatting and even after JSON_NUMERIC_CHECK
{"cols":[{"label":"Godina","type":"string"},{"label":"Odluka","type":"number"},{"label":"glasnik","type":"number"}],"rows":[{"c":[{"v":"Stambenog susjedstva - Stubi\u010dki Trnac - I.ID"},{"v":2014},{"v":2014}]},{"c":[{"v":"Prostorni plan ure\u0111enja Grada Krapine - IV. ID"},{"v":2013},{"v":2015}]},{"c":[{"v":"Prostorni plan ure\u0111enja Grada Donja Stubica - I ID"},{"v":2014},{"v":2015}]},{"c":[{"v":"Generalni urbanisti\u010dki plan Grada Krapine - V.ID"},{"v":2015},{"v":2016}]}]}
And here is JS:
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var data = new google.visualization.DataTable(<?php echo $jsonTable;?>);
chart.draw(data);
After running this whole block of code, I get this error
Cannot read property 'v' of undefined
Is there something wrong with PHP code?
1.Maybe there is problem with date formatting?
Why do I get some weirdly formatted JSON Example -- *Stambenog susjedstva - Stubi\u010dki Trnac - I.ID when I should be getting instead of this ->Stubi\u010dki this-> Stubički
When I run SQL i get something like this (example below:)
+-----------+------------------+-----------------+
| name| | start_date | end_Date |
+-----------+------------------+-----------------+
| example_1 | 2014-06-06 | 2014-12-27 |
| example_1 | 2013-12-31 | 2015-06-07 |
| example_1 | 2016-06-06 | 2015-12-31 |
+-----------+------------------+-----------------+
*
I want to get something like this:
https://jsfiddle.net/api/post/library/pure/
UPDATE 1
So, I've managed to fix some of the addressed issues:
First, problem with weirdly formatted JSON, fixed with JSON_UNESCAPED_UNICODE
So, instead of this code:
$jsonTable = json_encode($table,JSON_NUMERIC_CHECK);
I used this :
$jsonTable = json_encode($table,JSON_UNESCAPED_UNICODE);
On the timeline note I've managed to successfully render timeline chart,but on x axis, instead of years and date it shows me hours.I believe that i've missed something when transforming from query to json.
(as seen in picture below)
I used this block of PHP code:
try {
$db = connectPDO();
$result = $db->query("SELECT naziv_plan, objava_odluke, datum_stupanja_glasnika
FROM ispu_plan
WHERE datum_donosenja_plana
BETWEEN '2014-01-01'
AND CURDATE()
ORDER BY datum_donosenja_plana ASC");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Naziv plana', 'type' => 'string'),
array('label' => 'Odluka', 'type' => 'datetime'),
array('label' => 'glasnik', 'type' => 'datetime')
);
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) $r['naziv_plan']);
$temp[] = array('v' => (int) strtotime($r['objava_odluke']));
$temp[] = array('v' => (int) strtotime($r['datum_stupanja_glasnika']));
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table,JSON_UNESCAPED_UNICODE);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
And in JSON i get something like this 1402005600 for start date and in my table is formated like this 2014-06-06 and i believe that i need to get something like this 2014, 6, 6 to properly render and calculate timeline chart.
Please help with my lifetime crisis :)
UPDATE 2
Using whitehat knowledge and directions I'm feeling it that I'm one step closer to finally render this abomination :) Meanwhile, using directions and code that WhiteHat provided i created this:
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Godina', 'type' => 'string'),
array('label' => 'Odluka', 'type' => 'date'),
array('label' => 'glasnik', 'type' => 'date')
);
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$date1 = new DateTime();
$date2 = "Date(".date_format($date1, 'Y').", ".((int) date_format($date1, 'm') - 1).", ".date_format($date1, 'd').")";
$temp = array();
$temp[] = array('v' => (string) $row['naziv_plan']);
$temp[] = array('v' => (string) $date2);
$temp[] = array('v' => (string) $date2);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table,JSON_NUMERIC_CHECK);
Output of json is this:
{"cols":[{"label":"Godina","type":"string"},{"label":"Odluka","type":"date"},{"label":"glasnik","type":"date"}],"rows":[{"c":[{"v":"Stambenog susjedstva - Stubi\u010dki Trnac - I.ID"},{"v":"Date(2016, 8, 30)"},{"v":"Date(2016, 8, 30)"}]},{"c":[{"v":"Prostorni plan ure\u0111enja Grada Krapine - IV. ID"},{"v":"Date(2016, 8, 30)"},{"v":"Date(2016, 8, 30)"}]},{"c":[{"v":"Prostorni plan ure\u0111enja Grada Donja Stubica - I ID"},{"v":"Date(2016, 8, 30)"},{"v":"Date(2016, 8, 30)"}]},{"c":[{"v":"Generalni urbanisti\u010dki plan Grada Krapine - V.ID"},{"v":"Date(2016, 8, 30)"},{"v":"Date(2016, 8, 30)"}]}]}
And i get timeline, but without lines :(
Something like this:
And this two errors:
Expected number, "MNaN,0LNaN,40.992
Error: attribute x: Expected length, "NaN"
UPDATE 3
Ok, I believe that I've manage somehow, and it works. Here is code below, hope it helps someone. Once again thank you WhiteHat :)
try {
$db = connectPDO();
$result = $db->query("SELECT naziv_plan, objava_odluke, datum_stupanja_glasnika
FROM ispu_plan
WHERE datum_donosenja_plana
BETWEEN '2014-01-01'
AND CURDATE()
ORDER BY datum_donosenja_plana ASC ");
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Godina', 'type' => 'string'),
array('label' => 'Odluka', 'type' => 'date'),
array('label' => 'glasnik', 'type' => 'date')
);
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
// here I added rows in DateTime function, that was missing
$date1 = new DateTime($row['objava_odluke']);
$date2 = "Date(".date_format($date1, 'Y').", ".((int) date_format($date1, 'm') - 1).", ".date_format($date1, 'd').")";
$date3 = new DateTime($row['datum_stupanja_glasnika']);
$date4 = "Date(".date_format($date3, 'Y').", ".((int) date_format($date3, 'm') - 1).", ".date_format($date3, 'd').")";
$temp = array();
$temp[] = array('v' => (string) $row['naziv_plan']);
$temp[] = array('v' => (string) $date2);
$temp[] = array('v' => (string) $date4);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table,JSON_NUMERIC_CHECK);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
Picture, to prove it:
Im generating Chart4PHP.
In sample it takes data like this
$p->data = array(array(array("2010/10",-48),array("2011/01",238),array("2011/02",395)));
I have array "rows" constructed of row[date][units].
Im storing it in this way:
$rows = array();
for(...)
{
$row[date] = $mydate;
$row[units]= $myunits;
$rows[]=$row;
}
What I should make additionally to be able to use it as $p->data = $rows;
To add the extra array container, call array() with the rows array as the argument.
$data = array(array('date' => "2010/10", 'units' => -48),
array('date' => "2011/01", 'units' => 238),
array('date' => "2011/02", 'units' => 395));
foreach ($data as $d) {
$mydate = $d['date'];
$myunits = $d['units'];
$rows[] = array($mydate, $myunits);
}
$p->data = array($rows);
I am having a weird problem: I fired the same query select DateSpan, PUE from GF.dbo.PUE Data where DateSpan between '2013-10-01 12:00:00.000' and '2013-10-31 12:00:00.000' in SQL Server and getting proper result.
2013-10-01 12:00:00.000 1.66402976232178
2013-10-02 12:00:00.000 1.58132003529595
..
..
However when I fetch the same query through PHP script, it loses 1st day. Don't know the reason.
SELECT DateSpan, PUE
FROM [GF].[dbo].[PUEData]
where (DateSpan >= '$stdate' AND DateSpan < '$enddate')
Probably the problem is with later array formulation -
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => $metric , 'type' => 'number')
);
$result=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
while($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$temp = array();
$temp[] = array('v' => (string) $r['DateSpan']);
$temp[] = array('v' => (float) $r[$metric]);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table,JSON_NUMERIC_CHECK);
Many thanks!
I think I'm close to completing the passing of MySQL data to Google Charts through JSON/AJAX. I am able to output a JSON string in the correct format but it is not outputting any SQL data. I've searched everywhere for a solution with no results. Anyone see what is missing from the code?
JSON output
{"cols":[{"id":"","label":"projid","type":"string"},{"id":"","label":"hours","type":"number"}],"rows":[{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]}]}
PHP->JSON
<?php
// -----> Query MySQL and parse into JSON below. <------
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
require_once ("Includes/session.php");
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
$recId = null;
$projid = null;
$hours = null;
$recId = $_GET['id'];
$projid = $_GET['projid'];
$hours = $_GET['hours'];
$query = "SELECT projid, hours FROM hours WHERE id = ?";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('d', $recId);
$statement->execute();
$results = $statement->get_result();
$rows = array();
$table = array();
$table['cols'] = array(
array('id' => "",'label' => 'projid', 'type' => 'string'),
array('id' => "",'label' => 'hours', 'type' => 'number')
);
/* Extract the information from $result */
while ($r = $results->fetch_assoc()) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['projid']);
// Values of each slice
$temp[] = array('v' => (int) $r['hours']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
echo $jsonTable;
?>
The following code returned the correct array for Google Charts. Google Charts - JSON Data
<?php
// -----> Query MySQL and parse into JSON below. <------
require_once ("Includes/connectDB.php");
$result = $databaseConnection->query("SELECT projid, hours FROM alloc_hours");
$table = array();
$table['cols'] = array(
array('id' => "", 'label' => 'projid', 'pattern' => "", 'type' => 'string'),
array('id' => "", 'label' => 'hours', 'pattern' => "", 'type' => 'number')
);
$rows = array();
while ($nt = $result->fetch_assoc())
{
$temp = array();
$temp[] = array('v' => $nt['projid'], 'f' =>NULL);
$temp[] = array('v' => $nt['hours'], 'f' =>NULL);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
Array
{"cols":[{"id":"","label":"projid","pattern":"","type":"string"},{"id":"","label":"hours","pattern":"","type":"number"}],"rows":[{"c":[{"v":"2","f":null},{"v":"8","f":null}]},{"c":[{"v":"1","f":null},{"v":"6","f":null}]},{"c":[{"v":"3","f":null},{"v":"20","f":null}]},{"c":[{"v":"2","f":null},{"v":"10","f":null}]},{"c":[{"v":"4","f":null},{"v":"5","f":null}]},{"c":[{"v":"1","f":null},{"v":"30","f":null}]}]}
Try replacing this line:
$statement->store_result();
with:
$results = $statement->get_result();
and replace the foreach loop with a while loop:
while ($r = $results->fetch_assoc()) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['projid']);
// Values of the each slice
$temp[] = array('v' => (int) $r['hours']);
$rows[] = array('c' => $temp);
}
That should get the query to return results. You don't need the lines:
$statement->bind_result($projid, $hours);
$statement->fetch();