Create PieChart with google chart api and php - 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
));
}

Related

How can i create a LineString geoJson with data from data base?

ok, so I know how to convert data from php to geojson format into point types but i dont understand how can I make this into a lineString type here is the code, so the question is how can i get the coordinates data into one array :
include('testcon.php');
$query=pg_query($connect,"SELECT number, state, data, latitude,
long "
. "FROM schema.table "
. "WHERE number = '63' AND "
. "data BETWEEN '2018-12-01 00:00:00' and '2018-12-01 23:59:59'
limit 200 ");
# Try query or error
# Build GeoJSON feature collection array
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
# Loop through rows to build feature arrays
while($row = pg_fetch_array($query)) {
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
# Pass Longitude and Latitude Columns here
'coordinates' => array($row['long'], $row['lat'])
),
# Pass other attribute columns here
'properties' => array(
'indicativ' => $row['number'],
'stare' => $row['state'],
)
);
# Add feature arrays to feature collection array
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
?>
Solved it
$pointlist=array();
while($row = pg_fetch_assoc($query)) {
$pointlist[]=array($row['long'], $row['lat']);
};
# Build GeoJSON feature collection array
$geojson = array(
'type' => 'FeatureCollection',
'features' => array(
#);
#$feature = array(
'type' => 'Feature',
'geometry' => array(
'type'=> 'LineString',
'coordinates'=> $pointlist
)));
i create an empty array and then looped through all the data from lat and long columns and than in coordinates i got the variabel

create JSON with php

Sorry if this seems obvious but all the searches I am doing for this are returning complex answers and I have been struggling with this all day... I have been trying to create json data in PHP and really I want to send variables into the json data. I have not been able to do that so I followed a tutorial online and copied the code exactly yet i'm still not getting an output in my local host.. Please can somebody put me out of my misery...
<?php
$jsonData = new stdClass();
$people = array(
array(
'name' => 'Luci',
'age' => 25,
'sex' => 'female'
),
array(
'name' => 'John',
'age' => 27,
'sex' => 'male')
),
array(
'name' => 'Peter',
'age' => 22,)
'sex' => 'male'
)
);
$jsonData->source = "Program Knowledge";
$jsonData->published = date('Y-m-d H:s:i;');
$jsonData->status = true;
$jsonData->people = $people;
echo json_encode($jsonData);
?>
eventually I was going to try
$var = 123456;
$jsonData->codeid = $var
but I need to figure out just how to get it so work with data I have typed in.
Many thanks..!!
'sex' => 'male')
'age' => 22,)
Need to remove the parenthesis from these two lines, they're parsing errors

Cannot autocomplete other textfields using CJuiAutoComplete

I have a model that has fields id_peg, nama_peg, and jabatan_peg. So here's what I wanna do:
Autosuggestion that shows the list ofid_peg as I type in the text field id_peg
When I select the suggested id_peg, the fields nama_peg and jabatan_peg are autocompleted based on that corresponding selected value (retrieved from database)
I've been trying to do the first one and I did it. But I'm stuck at the second one.
This is what I did:
view/melaporkan.php:
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name' => 'test1',
'source' => $this->createUrl('search'),
// additional javascript options for the autocomplete plugin
'options' => array(
'showAnim' => 'fold',
'select' => 'js:function(event, ui) {
$('#nama_peg').val(ui.item.nama_peg);
$('#jabatan_peg').val(ui.item.jabatan_peg);
}',
),
));
controllers/sitecontroller.php
public function actionSearch() {
$res = array(0 => array('id' => 1, 'value' => "id_peg"), 1 => array('id' => 2, 'value' => "jabatan_peg"), 2 => array('id' => 2, 'value' => "nama_peg"));
if (isset($_GET['term'])) {
$qtxt = "SELECT id_peg FROM pegawai WHERE id_peg LIKE :id_peg";
$command = Yii::app()->db->createCommand($qtxt);
$command->bindValue(":id_peg", '%' . $_GET['term'] . '%', PDO::PARAM_STR);
$res = $command->queryColumn();
}
echo CJSON::encode($res);
Yii::app()->end();
}
All it did was autosuggest for id_peg. When clicked some random id_peg, nama_peg and jabatan_peg were still empty.
What did I do wrong?
Actually the problem is controllers/sitecontroller.php page.
You are sending only id_peg as JSON format but trying to get as ui.item.jabatan_peg.
It is always better to send your value as
[{"id":"Caprimulgus europaeus","value":"European Nightjar"}] pattern
and get the value ui.item.value at your select function.

How to search in fulltext index using php in mongodb

I'm using mongodb 2.4 and added fulltext index to the "title" field in one the collection. How should I search something in that field using php?
This is the code I use right now:
$params = array(
'_id' => array(
'$gt' => (int)$gt
)
);
$r = $this->collection->find( $params )->limit($limit);
This seem to be the answer to my question:
<?php
$result = $db->command(
array(
'text' => 'bar', //this is the name of the collection where we are searching
'search' => 'hotel', //the string to search
'limit' => 5, //the number of results, by default is 1000
'project' => Array( //the fields to retrieve from db
'title' => 1
)
)
);
http://www.php.net/manual/en/mongodb.command.php#111891

Get value from custom category attribute

I am trying to get the value from a custom category attribute in Magento. The attribute is a select field and is been made with the install script below:
$this->startSetup();
$this->addAttribute('catalog_category', 'category_categorycolor', array(
'group' => 'General Information',
'input' => 'select',
'type' => 'varchar',
'label' => 'Categorie kleur',
'backend' => '',
'visible' => 1,
'required' => 0,
'user_defined' => 1,
'option' => array (
'value' => array('yellow' => array('Geel'),
'purple' => array('Paars'),
'blue' => array('Blauw'),
'red' => array('Rood'),
'orange' => array('Oranje'),
'green' => array('Groen'),
'darkblue' => array('Donkerblauw'),
'lightgreen' => array('Lichtgroen'),
)
),
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));
$this->endSetup();
Unfortunately only getting numbers and not text value. I use this line to retrieve the value:
<?php $_category_categorycolor = $_category->getData('category_categorycolor'); if($_category_categorycolor): ?> <?php echo $_category_categorycolor; ?> <?php endif; ?>
Can someone help me?
Something like this:
$category_id = '10';
$attribute_code = 'category_categorycolor';
$category = Mage::getModel('catalog/category')->load($category_id);
echo $category->getResource()->getAttribute($attribute_code)->getFrontend()->getValue($category);
The sollution is pretty messy (the only one I know of).
$opt = array(); // will contain all options in a $key => $value manner
$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_category', 'category_categorycolor');
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);
foreach ($options as $o) {
$opt[$o['value']] = $o['label'];
}
}
$categoryColorId = $_category->getData('category_categorycolor');
$categoryColorLabel = $opt[$categoryColorId];
// if you have problems, do a Zend_Debug::dump($opt);
// - it should contain an array of all the options you added
Didn't test it out, let me know if it works or not.
PS: can't reply to your comment, not sure why. What does $opt contain ?
The numbers you are getting back are the id's of each value in the dropdown. You have to load the dropdown values too.
See the following page. It helped me understand this.
http://www.sharpdotinc.com/mdost/2009/04/06/magento-getting-product-attributes-values-and-labels/

Categories