Getting data from PHP to JSON - php

So, I want to create dynamic donut chart, where the datas are from mySql database. But, the problem is in that chart, the datas get from JSON.
My question, how to use datas from PHP to be use for JSON datas. here're my progress so far :
<?php
$query_A = "SELECT COUNT(category) as catg FROM mydata ORDER BY category";
$result_A = mysql_query($query_A);
$query_B = "SELECT COUNT(category) as catg FROM mydata ORDER BY category";
$result_B = mysql_query($query_B);
//Print JSON
$prefix = '';
"[\n";
while ( $row_A = mysql_fetch_assoc( $result_A ) ) {
$prefix . " {<br>";
' "category": "' . "A" . '",' . "<br>";
' "value": ' . $row_A['catg'] . ',' . "<br>";
" }";
$prefix = ",\n";
}
while ( $row_B = mysql_fetch_assoc( $result_B ) ) {
$prefix . " {<br>";
' "category": "' . "B" . '",' . "<br>";
' "value": ' . $row_B['catg'] . ',' . "<br>";
" }";
$prefix = ",\n";
}
"\n]";
?>
And here're JSON datas from that donut chart :
<script type="text/javascript">
var chart = AmCharts.makeChart( "chartdiv", {
"type": "pie",
"theme": "light",
"dataProvider": [ {
"title": "New",
"value": 200
}, {
"title": "Returning",
"value": 9899
}, {
"title": "Back",
"value": 900
} ],
"titleField": "title",
"valueField": "value",
"labelRadius": 10,
"radius": "42%",
"innerRadius": "60%",
"labelText": "[[title]]",
"export": {
"enabled": true
}
} );
</script>
I want to use my mysql datas for that JSON datas. Thank you

There's a handy function called json_encode. Simply run your data through this function.
$json = json_encode($data); // returns a JSON string
By the way, have you tried googling for "PHP create JSON" or something similar? The time it took you to write this question, you would already have found a solution. Not to mention the time you wasted on trying to create the JSON yourself.
Just saying, you can save a lot of time by asking a search engine … you are usually not the first to have a particular problem.

I can't understand why there are two identical queries but that said.
<?php
$query_A = "SELECT COUNT(`category`) as 'catg' FROM `mydata` ORDER BY `category`";
$result_A = mysql_query( $query_A );
$query_B = "SELECT COUNT(`category`) as 'catg' FROM `mydata` ORDER BY `category`";
$result_B = mysql_query( $query_B );
if( $result_A ){
$data=array();
while ( $row_A = mysql_fetch_assoc( $result_A ) ) {
$data[]=array('category'=>'A', 'value'=>$row_A['catg'] );
}
$json_A=json_encode( $data );
}
if( $result_B ){
$data=array();
while ( $row_B = mysql_fetch_assoc( $result_B ) ) {
$data[]=array('category'=>'B', 'value'=>$row_B['catg'] );
}
$json_B=json_encode( $data );
}
?>
Then, in your javascript you could do this:-
var json_a=<?php echo $json_A;?>;
var json_b=<?php echo $json_B;?>;

Related

PHP Traverse through JSON using foreach

I had been following this guide to create an app using two different APIs but the guide is old and so one of the APIs does not work like it did in the guide. I am trying to grab coordinates from google geocoding API and stick them into Places for Web. I am new to PHP, so I was following the guide's example to traverse a JSON object but have been stuck all night trying to get it to work.
Here is the JSON object from the place search API
{
"html_attributions":[ ],
"results":[
{
"geometry":{ },
"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id":"d4b0fb0f7bf5b2ea7df896a0c120a68efae039cf",
"name":"Guadalajara Mexican Grill & Cantina",
"opening_hours":{ },
"photos":[
{
"height":2952,
"html_attributions":[ ],
"photo_reference":"CmRaAAAAfO4JKUaO8vCFM2dcu5LMu4mA4_HXQGJ1FyAnyJUre_kD6VOWiQj7tBEECx4AAct5AORIKipSYWg-Zprjlf8o-SFd7mBRGMXMVMwodFZ5KMLwPYPUhBnTTehGPkb9275pEhCkAqMwfmK29vYenk1wdwFvGhSIHR8ch6FONc99tGn4rVnesbuteg",
"width":5248
}
],
"place_id":"ChIJ27es4SWa3IARcvjmt3xL2Aw",
"price_level":2,
"rating":4.4,
"reference":"CmRRAAAA7Rx-l7juDX-1or5dfpK6qFcZ0trZ9cUNEUtKP2ziqHb2MhOE6egs-msJ2OdFKEuHhuNe-3Yk6yxUYwxCBqhDT3ci8pYZI4xYhPGyyDgDenbEU_8k84JiEtCGvj4bdIR0EhDR2Pqte5_kDUcCC9PJFVknGhQomvD4d7NBIhCFxI4i2iEc0w9UiA",
"scope":"GOOGLE",
"types":[ ],
"vicinity":"105 North Main Street, Lake Elsinore"
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"status":"OK"
}
I am trying to grab all the photo references into an array maybe?, and then plug them into google's Place Photos API. Here is my attempt at that:
UPDATE
<?php
if(!empty($_GET["location"])){
//$API_key = "";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($_GET['location']) .
'&key=';
$maps_json = file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
'location=$lat,$lng' .
'&radius=1500' .
'&rankby=distance' .
'&key=';
$places_json = file_get_contents($places_url);
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array as $item) {
var_dump($places_array );
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>What is Here?</title>
</head>
<body>
<h1>Type in a location</h1>
<p>This program will display pictures of places to go in that area</p>
<form action ="">
<input type ="text" name ="location"/>
<button type ="submit">Go!</button>
</form>
<br/>
<?php
echo "$lat $lng";
?>
Just can't seem to get the foreach loop to do anything
the invalid request means wrong url or bad parameters
if $lat and $lng are variables then the interpolation wont work with single quotes try using double quotes like this
"location=$lat,$lng"
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key=mykey';
you should remove radius or distance you cant get both its on the docs
https://developers.google.com/places/web-service/search?hl=en-419
here is my modified code that works on localhost please notice the $contextOptions you should not copy this on your code this is a workaround to make file_get_contents work on my machine
after that the foreach should be easy since is only an array look at the code
$thelocation = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";
$thekey = "someapikey";
$maps_url = 'https://' .
'maps.googleapis.com/' .
'maps/api/geocode/json' .
'?address=' . urlencode($thelocation) .
'&key=' . $thekey;
$contextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$maps_json = file_get_contents($maps_url, 0, stream_context_create($contextOptions));// file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][0]['geometry']['location']['lat'];
$lng = $maps_array['results'][0]['geometry']['location']['lng'];
$places_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?' .
"location=$lat,$lng" .
'&rankby=distance' .
'&key='.$thekey;
//https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&rankby=distance&key=
$places_json = file_get_contents($places_url,0, stream_context_create($contextOptions));
$places_array = json_decode($places_json, true);
if (!empty($places_array)) {
foreach ($places_array["results"] as $item) {
echo $item["name"]."<br>";
}
}
this prints....easy
AVEonline.co
KRAV MAGA GLOBAL WORLD MAP
Mark Carvalho
Amyan
Moving the Planet
Sosta in Camper
NosCode
GLOBAL BUZZ
OptiClean
JI-SU TELECOM
Reel Thrillz
Clío Reconstrucción Histórica
AprimTek
Hayjayshop
NHAV
gitanos.cat
Being Digitall
Directory+
AdExperts
Optical Spectroscopy and Nanomaterials Group
The $lat,$lng variables or the API call is your first problem, and the foreach loop is the second.
The json_decode($someJSON, true); creates an associative array from your json, so you can't use the -> arrows, those are for the objects. More about this.
There's no $item->photo_reference, use:
$results = $places_array["results"];
foreach ($results as $item) {
echo $item["photos"]["photo_reference"];
}

Create json api for mobile application using php mysql

Hello I need to create a json encode api for the code which i am building
Currently my project have 3 tables item table,payment table and sms table
item table contains the details of my project and the item table is linked to payment and sms table
i am listing the json form which i want to make
{
"Data": {
"Projects": [{
"id": "10023",
"Info": "Arabic project info ",
"paymentMethods": {
"Bank": [{
"accname": "Zakat Acc",
"accnameEn": "حساب الزكــــــاة",
"country": "UAE",
"acc": "0034430430012"
}, {
"accname": "Zakat Acc",
"accnameEn": "حساب الزكــــــاة",
"country": "UAE",
"acc": "00344304332412"
}],
"SMS": [{
"operatorEn": "etisalat",
"shortcode": "4236",
"operator": "إتصالات"
}, {
"operatorEn": "etisalat",
"shortcode": "4346",
"operator": "إتصالات"
}],
"CC": {
"-URL":
"http://www.sharjahcharuty.org/donations/"
}
}
}, {
"id": "10026",
"Info": "Arabic project info ",
"InfoEn": "project info in english",
"paymentMethods": {
"Bank": [{
"accname": "Zakat Acc",
"accnameEn": "حساب الزكــــــاة",
"country": "UAE",
"acc": "0034430430012"
}, {
"accname": "Zakat Acc",
"accnameEn": "حساب الزكــــــاة",
"country": "UAE",
"acc": "00344304332412"
}],
"SMS": [{
"operatorEn": "etisalat",
"shortcode": "4236",
"operator": "إتصالات"
}, {
"operatorEn": "etisalat",
"shortcode": "4346",
"operator": "إتصالات"
}],
"CC": {
"-URL": "http://www.sharjha.org/donations/"
}
}
}]
}
}
I have created php code for the system
But this code i have create using brackets and seperated by queries but this system not giving the result what i expected
echo $string='{"Data":{';
//echo $string='"Projects":';
$sql2 = "SELECT * FROM wg_items where cat_id=6007;";
$query = $this->db->query($sql2);
echo $string='"Projects":';
echo $string='[';
$intcount=0;
$scateg="";
if ($query->num_rows() > 0) {
foreach ($query->result() as $row){
//$jsonrows[]=array("id"=>$row->cat_id,"name"=>$row->item_name);
echo $string='{';
echo $string = 'id:'.$row->item_id;
echo $string=',';
echo $string = 'name:'.$row->item_name;
echo $string=',';
//-------------------------------------------------------------//
$hasComma = false;
echo $string='"paymentmethods":';
echo $string='"Bank":[';
$sql2 = "SELECT * FROM paymentmethods where cid=587 ";
$query = $this->db->query($sql2);
foreach ($query->result() as $row){
echo '{';
echo $string = 'accname:'.$row->acc.',' ;
echo $string = 'country:'.$row->IBAN.',' ;
echo $string = 'Iban:'.$row->Bankname.',' ;
echo $string = 'Bankname:'.$row->Bankname.',' ;
echo $string = '},';
}
echo $string = '],';
echo $string='"SMS":[';
$sql3 = "SELECT * FROM sms where cid=537 ";
$query = $this->db->query($sql3);
$hasComma = false;
foreach ($query->result() as $rows){
echo '{';
echo 'Operator:'.$rows->operator.',' ;
echo 'shortcode:'.$rows->shortcode.',';
echo 'keyword:'.$rows->keyword.',';
echo 'price:'.$rows->price;
echo $string = '},';
if($hasComma = TRUE)
{
}
$hasComma = TRUE;
}
echo $string = '}],';
echo $string='"CC":{';
echo $string3='"-URL:"';
echo $string3='"HTTP:SHARJAHCHARTITY.COM"';
ECHO '}}}';
echo ',';
}
echo ']}}}';
You are not suppose to append strings to create a json string.
Create an array which holds the data and wrap it with json_encode() function
For ex:
<?php
$array_data=[];
$array_data['firstname']="Rafique";
$array_data['lastname']="Mohammed";
$array_data['email']="plus.arr#gmail.com";
// or any data which you want in json
$json_output=json_encode($array_data);
echo $json_output;
OUTPUT :
{"firstname":"Rafique","lastname":"Mohammed","email":"plus.arr#gmail.com"}
UPDATE 2 :
In your case
<?php
//.. your code
if ($query->num_rows() > 0) {
foreach ($query->result() as $row){
$jsonrows=array("id"=>$row->item_id,"name"=>$row->item_name);
$jsonrows["paymentmethods"]=array("Bank"=>[]);
$sql2 = "SELECT * FROM paymentmethods where cid=587 ";
$query = $this->db->query($sql2);
foreach ($query->result() as $row){
//convert bank as array
$jsonrows["paymentmethods"]["Bank"][] = array(
"accname"=>$row->acc,
"country"=>$row->IBAN,
"Iban"=>$row->Bankname,
"Bankname"=>$row->Bankname );
}
//DO IT FOR REST OF THE CODE

Scrape second HTML table

I'm trying to extract the main table from a website, convert it to JSON, but the tables before the one I want are obstructing the code I'm using. The code I'm using:
<?php
$singles_chart_url = 'http://www.mediabase.com/mmrweb/allaboutcountry/Charts.asp?format=C1R';
// Get the mode from the user:
$mode = $_GET['chart'];
// This is an array of elements to remove from the content before stripping it:
$newlines = array("\t", "\n", "\r", "\x20\x20", "\0", "\x0B");
switch($mode)
{
// They want the Singles chart, or haven't specified what they want:
case 'singles':
case '':
default:
$content = file_get_contents($singles_chart_url);
$start_search = '<table width="100%" border="0" cellpadding="2" cellspacing="2">';
break;
}
$content = str_replace($newlines, "", html_entity_decode($content));
$scrape_start = strpos($content, $start_search);
$scrape_end = strpos($content, '</table>', $scrape_start);
$the_table = substr($content, $scrape_start, ($scrape_end - $scrape_start));
// Now loop through the rows and get the data we need:
preg_match_all("|<tr(.*)</tr>|U", $the_table, $rows);
// Set the heading so we can output nice XML:
switch($_REQUEST['format'])
{
case 'json':
default:
header('Content-type: application/json');
$count = 0;
foreach($rows[0] as $row)
{
// Check it's OK:
if(!strpos($row, '<th'))
{
// Get the cells:
preg_match_all("|<td(.*)</td>|U", $row, $cells);
$cells = $cells[0];
$position = strip_tags($cells[0]);
$plus = strip_tags($cells[1]);
$artist = strip_tags($cells[2]);
$weeks = strip_tags($cells[3]);
echo "\n\t\t" . '{';
echo "\n\t\t\t" . '"position" : "' . $position . '", ';
echo "\n\t\t\t" . '"plus" : "' . $plus . '", ';
echo "\n\t\t\t" . '"artist" : "' . $artist . '", ';
echo "\n\t\t\t" . '"noWeeks" : "' . $weeks . '" ';
echo ($count != (count($rows[0]) - 2)) ? "\n\t\t" . '}, ' : "\n\t\t" . '}';
$count++;
}
}
echo "\n\t" . ']';
echo "\n" . '}';
break;
}?>
The website I'm trying to scrape. The goal is to retrieve json results of the table beginning after LW, TW, Artist, Title, etc. The above returns:
{
"chartDate" : "",
"retrieved" : "1444101246",
"entries" :
[
{
"position" : "7 DayCharts",
"plus" : "Country Past 7 Days -by Overall Rank Return to Main Menu ",
"artist" : " ",
"noWeeks" : "",
"peak" : "",
"points" : "",
"increase" : "",
"us" : ""
},
]
}
instead of
{
"chartDate" : "",
"retrieved" : "1444101246",
"entries" :
[
{
"position" : "2",
"plus" : "1",
"artist" : "KENNY CHESNEY",
"noWeeks" : "Save It For A Rainy"", etc . etc.
},
]
}
What could I add to the code above to retrieve that table?
Update
The problem is the match pattern.
After following statement,
$content = str_replace($newlines, "", html_entity_decode($content));
Some characters are replace or removed, such as " and Some tags are being in UPPERCASE. Hence you are always getting 0 as strpos for $scrape_start no matter what $start_search contains.
So you have to search like,
$start_search ='<TBODY>';
Working code on PhpFiddle

Strange behavior after ajax call

I'm working on a "subscription module" for a website, everything works fine except
the Ajax part.
When I click the first time on "subscribe" the button changes to "unsubscribe", but if i click on "unsubscribe" button again without refreshing the page, the button changes to "subscribe" and than to "unsubscribe" again.
Like if I clicked it twice.
This is what I can see from "chrome -> network tab"
engine/ajax/mywatch.php?subscribe_id=3385&action=plus&skin=Default
engine/ajax/mywatch.php?subscribe_id=3385&action=minus&skin=Default
html
<a id="subscript-id-3385" onclick="doMywatch('3385', 'plus'); return false;" >subscribe</a>
javascript
<script>
function doMywatch(a,b){ShowLoading("");$.get(root+"engine/ajax/mywatch.php",{subscribe_id:a,action:b,skin:skin},function(b){HideLoading("");$("#subscript-id-"+a).html(b)});return!1}
</script>
php
if( $_GET['action'] == "plus" ) {
echo <<<HTML
<script>
alert('plus ');
</script>
HTML;
$row = $db->super_query("SELECT subscriptions FROM " . PREFIX . "_mywatch WHERE user_id={$member_id['user_id']}" );
$list = explode(",", $row['subscriptions']);
foreach ( $list as $daten ) {
if( $daten == $id ) $achecker = "stop";
}
$error = "";
if( $achecker != "stop" ){
$list[] = $id;
$subsc = $db->safesql(implode( ",", $list ));
//$subsc = implode( ",", $list );
if( $row['subscriptions'] == "" ) $subsc = $id;
$db->query( "UPDATE " . PREFIX . "_mywatch set subscriptions='$subsc' where user_id = '{$member_id['user_id']}'" );
}
$buffer = "<a onclick=\"doMywatch('" . $id . "', 'minus'); \" title=\"" . $lang['news_minfav'] . "\">unsubscribe</a>";
} elseif( $_GET['action'] == "minus" ) {
echo <<<HTML
<script>
alert('minus ');
</script>
HTML;
$error = "";
$row = $db->super_query("SELECT subscriptions FROM " . PREFIX . "_mywatch WHERE user_id={$member_id['user_id']}" );
$list = explode(",", $row['subscriptions']);
foreach ( $list as $daten ) {
if( $daten == $id ) $achecker = "stop";
}
if( $achecker == "stop" ){
$list = array_merge(array_diff($list, array($id)));
$subsc = $db->safesql(implode( ",", $list ));
//$subsc = implode( ",", $list );
$db->query( "UPDATE " . PREFIX . "_mywatch set subscriptions='$subsc' where user_id = '{$member_id['user_id']}'" );
}
$buffer = "<a onclick=\"doMywatch('" . $id . "', 'plus'); \" title=\"" . $lang['news_minfav'] . "\">Подписатся</a>";
} else
die( "error" );
$db->close();
#header( "Content-type: text/html; charset=" . $config['charset'] );
echo $buffer;
If I'm right, the first time you click susbcribe, you will go in the elseif( $_GET['action'] == "plus" ), then your output will be <a onclick=......>Unsubscibe</a> and will be put inside your previous <a id="subscript-id-3385">...</a> so you will have both click events for subscribe and unsubscribe in the same element, so this can lead to some strange behaviour. I suggest you to wrap your link in a div and update that div only.

Populate an associative select from a database

Here's my problem: I have two select fields in my web application.
The second one depends on the choice made on the first one. The first one is populated from my database with the classical:
<?php
//connection to database in an include file
$query = "SELECT DISTINCT platform
FROM Appversions";
$res = mysql_query($query);
while($row = mysql_fetch_array($res)) {
echo "<option value=\"\"" . $row['platform'] . "</option>\n";
}
?>
which is working just fine.
But then I need to populate my second select with a query that would look like:
SELECT version
FROM Appversions
WHERE platform = <choice made in first select>;
I understand that I need to use JavaScript with an onChange function call to do that, but I can't figure out what that function should look like or how it will have access to my query result.
Usually i have this jquery code:
$('#select1').change(function(){
if($(this).val() == ''){
$('#select2').attr('disabled', 'true');
}else{
var select1 = $(this).val();
$.getJSON('index.php',
{
option: "com_spin",
controller: "guest",
task: "getProvincieByRegionId",
idRegione: idRegione
},
function(json){
$('#select2').html(json.html);
}
);
$('#select2').removeAttr('disabled');
}
});
in php i have something like this (basically i return the html for the options:
Zend_Loader::loadClass ( 'Zend_Json' );
$idRegione = JRequest::getVar ( "idRegione" );
$modelProvince = new Spin_lkpprovincia ();
$provincie = $modelProvince->getElencoProvinciePerRegione ( $idRegione );
$html = "<option value=''>Selezionare una voce</option>";
foreach ( $provincie as $provincia ) {
$html .= "<option value='" . $provincia ['idProvincia'] . "'>" . $provincia ['nome'] . "</option>";
}
$json = array (
success => "OK",
html => $html );
$json = Zend_Json::encode ( $json );
echo $json;
die ();

Categories