How To generate json format from model in codeigniter - mysql

I Have Database :
enter image description here
how to query mysql in codeigniter model so that it can output json data like this :
enter code here</script">
$.ajax({
url: '?grid=true&tahun=' + tahuncikarang,
method: "GET",
success: function(data) {
var obj = JSON.parse(data);
}
Highcharts.chart('cikarang', {
chart: {
type: 'bar'
},
title: {
text: 'Highcharts multi-series drilldown'
},
subtitle: {
text: 'The <em>allowPointDrilldown</em> option makes point clicks drill to the whole category'
},
xAxis: {
type: 'category'
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true
}
}
},
series: [{
name: '2010',
data: obj.tahun1
}, {
name: '2014',
data: obj.tahun2
}],
drilldown: {
allowPointDrilldown: false,
series: [{
id: 'republican-2010',
name: 'Republican 2010',
data: [
['East', 4],
['West', 2],
['North', 1],
['South', 4]
]
}, {
id: 'democrats-2010',
name: 'Republican 2010',
data: ''
}, ]
}
});
}
});
I try in model :
function index($tahuncikarang)
{
$this->db->select('nama AS nama, CONCAT(nama,"-", tahun) AS drilldown, sum(nilai) AS y');
$this->db->where('tahun=2010');
$this->db->group_by('nama')
->group_by('tahun');
$tahuna1 = $this->db->get(self::$table5);
$tahuna2 = array();
foreach ($tahuna1->result() as $row) {
array_push($tahuna2, $row);
}
$this->db->select('nama AS nama, CONCAT(nama,"-", tahun) AS drilldown, sum(nilai) AS y');
$this->db->where('tahun=2014');
$this->db->group_by('nama')
->group_by('tahun');
$tahunb1 = $this->db->get(self::$table5);
$tahunb2 = array();
foreach ($tahunb1->result() as $row) {
array_push($tahunb2, $row);
}
$result = array();
$result['tahun1'] = $tahuna2;
$result['tahun2'] = $tahunb2;
return json_encode($result, JSON_NUMERIC_CHECK);
}

I read your question just before.
If you could use this query, you maybe get good results.
Thank you
$qy = $this->db->query("select concat(lower(nama),'-',tahun) as id,concat(nama,'-',tahun) as name,group_concat(concat(zone,'-' ,nilai),',') as data group by nama, tahun")->result_array();
$result = array();
foreach($qy as $row) {
$temp = array(
"id"=>$row['id'],
"name"=>$row['name'],
"data"=>array()
);
$array = explode(',',$row['data']);
foreach($array as $el) {
$temp['data'][]=explode('-',$el);
}
$result[] = $temp;
}
echo json_encode($result);

Related

Highcharts drilldown data from mysql

Im trying to use the drill down method for my chart similar to this: https://www.highcharts.com/demo/column-drilldown/sand-signika%5d%5b1%5d.
But I want to drilldown my data from YEARS,MONTHS,WEEKS & DAYS. How can I execute that? Heres my code:
$query = "SELECT sum(product_total) as total, YEAR(`date`) as year FROM confirm_order_product GROUP BY YEAR(date) ORDER BY date";
$result = $mysqli->query($query);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$salestotal[] = $row['total'];
$sdate[] = $row['year'];
}
$salesdate = json_encode($sdate, JSON_NUMERIC_CHECK);
$sales = json_encode($salestotal, JSON_NUMERIC_CHECK);
Container:
$(function() {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Sales Report'
},
xAxis: {
categories: <?php echo $salesdate; ?>
},
yAxis: {
title: {
text: 'Value'
},
},
tooltip: {
valuePrefix: '₱'
},
series: [{
name: 'Sales',
colorByPoint: true,
data:<?php echo $sales; ?>,
}],
});
});
This only displays per year.

DataTable Populate Ajax

I have a datatable js and I fill in with ajax (json), in my json, its return is several entries, I see this through the console, but, the datatable is only populated with the first json record.
My Code
$(document).ready(function()
{
$.ajax({
type : 'POST',
url : 'view/list/clients_1.php',
dataType: 'json',
cache: false,
success : function(result)
{
//pass data to datatable
console.log(result); // just to see I'm getting the correct data.
$('#my_table').DataTable({
"searching": false, //this is disabled because I have a custom search.
"bAutoWidth": false,
"bFilter": true,
"bLengthChange": false,
"responsive": true,
"aaData": [result], //here we get the array data from the ajax call.
"aoColumns": [
{ "sTitle": "#" },
{ "sTitle": "Name" },
{ "sTitle": "Work" }
]
});
}
});
Code of file: clients_1.php
$clients_sql =
"
SELECT
*
FROM
client
";
$result = mysqli_query($mysqli, $clients_sql);
$dataArray = array();
while( $row = mysqli_fetch_array($result) )
{
$dataArray[] = $row["client_id"];
$dataArray[] = $row["client_name"];
$dataArray[] = $row["client_work"];
}
echo json_encode($dataArray);
resolved
var table = $('#my_table').dataTable({
serverSide: true,
searching: false,
bAutoWidth:false,
bFilter: true,
bLengthChange: false,
responsive: true,
ajax: "view/lista/clientes_1.php",
dataSrc: 'data',
columns: [
{sTitle: "#", data: 'client_id' },
{sTitle: "Name", data: 'client_nome' },
{sTitle: "Work", data: 'client_work' }
]
}); // End: DataTable
$('#search-table').unbind();
$('#search-table').bind('keyup', function(e) {
//if(e.keyCode == 13) {
table.fnFilter(this.value);
// }
});
PHP
$result = mysqli_query($mysqli, $clients_sql);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
$results = [
"sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData" => $data
];
echo json_encode($results);
I recommend adding to the answer given by sNniffer
$data = [];
just above the while loop.
Otherwise, when there are no rows in the query (and the while loop is not executed), you get this warning from datatables

How to fix SyntaxError: Unexpected token &

I am sending a php coded in accordance with the json_encode function to a plantilla.twig where I want to graph a pie chart type and the browser shows me the following error in console uncaught SyntaxError: Unexpected token & ¨ and I red the line following data: [[& quot; Intermediate 17.5 inches & quot;, 2220]]
Controller Class
public function tiempoXEtapaAction()
{
$em = $this->getDoctrine()->getManager();
$servicepozo = $this->get('service.pozo');
$pozoActual = $servicepozo->getPozoActual();
$idpozo = $servicepozo->getPozoActual()->getId();
$activityCollections = $em->getRepository('ActividadBundle:ActividadDiariaCollection')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$intervalos = $em->getRepository('IntervaloBundle:Intervalo')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$actividades = $em->getRepository('ActividadBundle:ActividadDiaria')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$tiempoXIntervalo = array();
foreach ($activityCollections as $activityCollection) //Dias
{
$fechaActCole = $activityCollection->getFecha();
foreach ($intervalos as $intervalo) //Intervalos
{
if ($intervalo->getFechaInicio() <= $fechaActCole && $intervalo->getFechaFinal() >= $fechaActCole) {
$temp = array();
$temp[] = $intervalo.'';
foreach ($actividades as $actividad) //Actividades
{
if ($actividad->getCollection()->getId() == $activityCollection->getId()) {
$duracion[] = $actividad->getDuracion();
}
}
$temp[] = array_sum($duracion);
}
}
$tiempoXIntervalo[] = $temp;
}
return array('tiempoXIntervalo'=> (json_encode($tiempoXIntervalo)));
Template.Twig
title: {
text: 'Distribución de tiempo por Intervalo'
},
xAxis: {
reversed: false,
title: {
enabled: true,
text: 'Dias'
},
labels: {
formatter: function () {
return this.value;
}
},
maxPadding: 0.05,
showLastLabel: true,
allowDecimals: false,
min:0,
},
yAxis: {
max:0,
startOnTick: false,
title: {
text: 'Profundidad [m]'
},
labels: {
formatter: function () {
return this.value;
}
},
lineWidth: 2,
},
legend: {
enabled: true
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}h ({point.percentage:.1f}%)</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
data:{{tiempoXIntervalo}}
}]
});
});
</script>
You should check how to convert HTML entities
Also, there is an extra space in & quot;
It should be "
json_encode expects " so it should be ["Intermediate 17.5 inches",2220]
Thanks Fernando but your solution do not work for mi.
Apparently the problem was Twig autoescaping variables. I tried to use Twig's raw filter to skip autoescaping and it's work for mi. Here the solution
data: $.parseJSON('{{ tiempoXIntervalo | raw }}')

passsing data to https by JSON using JSONP

i had try many diffrent tutarials and examples from http://api.jquery.com/jQuery.getJSON/ and Post data to JsonP and saw many staffs about how to convert json data to jasonP but still i can not do it,is there any one could see how should i pass my data over https within my codes here which i am using highcharts to get data from my domain sql server which is in diffrent server than my webpages host.here is my codes:(i know which i should use ajax request but i dont know how in my case,if anyone know please HELP!) tnx.
getting data by getJASON over data.php which request from sql server to grab data:
var Options;
$(document).ready(function() {
Options = {
chart: {
renderTo: 'container2',
type: 'area',
borderColor: "#3366ff",
borderWidth:5,
zoomType : 'x'
},
title: {
text: 'Total Meeting_Logs Duration of Organization1 '
},
subtitle: {
text: ' '
},
credits:{
enabled:false
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 20,
//format data based on #datepicker which is html jquery ui date
//picker
formatter: function() {
return Highcharts.dateFormat('%l%p',
Date.parse(this.value +' UTC'));
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderRadius: 10,
borderWidth: 3
},
// Enable for both axes
tooltip: {
crosshairs: [true,true]
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
type: 'area',
name: '',
data: []
}]
}
// here i get my data from data.php within same server
$.getJSON("data.php", function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
});
//this function get user request for input time period and
//update in my domain
$(function() {
$( "#datepicker2" ).datepicker({
dateFormat: "yy-mm-dd",
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true,
onSelect: function(dateText, inst) {
$.getJSON("data.php?dateparam1="+dateText, function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
}
});
});
data.php:
`
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moh1368_Mrs_Lemoine", $con);
if (isset($_GET["dateparam"])) {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '".$_GET["dateparam"]."%'");
} else {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '2013-02-01%'");
}
$result['name'] = 'Foot Traffic Count';
while($r = mysql_fetch_array($sql)) {
$datetime = $r['timestamp_value'];
$result['category'][] = $datetime;
$result['data'][] = $r['traffic_count'];
}
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>`

Flexigrid in zend

i have a page post2.php which prints the json array like
{
page: 1,
total: 239,
rows: [{
id: '239',
cell: ['239', 'ZW', 'ZIMBABWE', 'Zimbabwe', 'ZWE', '716']
},
{
id: '238',
cell: ['238', 'ZM', 'ZAMBIA', 'Zambia', 'ZMB', '894']
},
{
id: '237',
cell: ['237', 'YE', 'YEMEN', 'Yemen', 'YEM', '887']
},
{
id: '236',
cell: ['236', 'EH', 'WESTERN SAHARA', 'Western Sahara', 'ESH', '732']
},
{
id: '235',
cell: ['235', 'WF', 'WALLIS AND FUTUNA', 'Wallis and Futuna', 'WLF', '876']
},
{
id: '234',
cell: ['234', 'VI', 'VIRGIN ISLANDS, U.S.', 'Virgin Islands, U.s.', 'VIR', '850']
},
{
id: '233',
cell: ['233', 'VG', 'VIRGIN ISLANDS, BRITISH', 'Virgin Islands, British', 'VGB', '92']
},
{
id: '232',
cell: ['232', 'VN', 'VIET NAM', 'Viet Nam', 'VNM', '704']
},
{
id: '231',
cell: ['231', 'VE', 'VENEZUELA', 'Venezuela', 'VEN', '862']
},
{
id: '230',
cell: ['230', 'VU', 'VANUATU', 'Vanuatu', 'VUT', '548']
}
]
}
and in zend views i am trying to do like
$(document).ready(function() {
$("#flex1").flexigrid({
url: '/public/**post2.ph**p',
dataType: 'json',
colModel: [{
display: 'ID',
name: 'id',
width: 40,
sortable: true,
align: 'center'
},
{
display: 'ISO',
name: 'iso',
width: 40,
sortable: true,
align: 'center'
},
{
display: 'Name',
name: 'name',
width: 180,
sortable: true,
align: 'left'
},
{
display: 'Printable Name',
name: 'printable_name',
width: 120,
sortable: true,
align: 'left'
},
{
display: 'ISO3',
name: 'iso3',
width: 130,
sortable: true,
align: 'left',
hide: true
},
{
display: 'Number Code',
name: 'numcode',
width: 80,
sortable: true,
align: 'right'
}
],
buttons: [{
name: 'Add',
bclass: 'add',
onpress: test
},
{
name: 'Delete',
bclass: 'delete',
onpress: test
},
{
separator: true
},
{
name: 'A',
onpress: sortAlpha
},
],
searchitems: [{
display: 'ISO',
name: 'iso'
},
{
display: 'Name',
name: 'name',
isdefault: true
}
],
sortname: "id"
sortorder: "asc",
usepager: true,
title: 'Countries',
useRp: true,
rp: 10,
showTableToggleBtn: true,
width: 700,
height: 255
});
});
this prints the flexigrid layout well.. but never gets the data.it keeps telling processing.
is there some problem in the json array or in the flexigrid calling... or in zend with json.
any suggestions to try out for this problem?
i tried out like this also
$.post("/public/server_processing1.php",{},function(data){
alert('hai');
alert(data);
}, "json");
and its not even alerting hai ..
full post2.php code is like this
<?
error_reporting(1);
function runSQL($rsql) {
$hostname = "localhost";
$username = "root";
$password = "root";
$dbname = "hms1";
$connect = mysql_connect($hostname,$username,$password) or die ("Error: could not connect to database");
$db = mysql_select_db($dbname);
$result = mysql_query($rsql) or die ('test');
return $result;
mysql_close($connect);
}
function countRec($fname,$tname,$where) {
$sql = "SELECT count($fname) FROM $tname $where";
$result = runSQL($sql);
while ($row = mysql_fetch_array($result)) {
return $row[0];
}
}
$page = $_POST['page'];
$rp = $_POST['rp'];
$sortname = $_POST['sortname'];
$sortorder = $_POST['sortorder'];
if (!$sortname) $sortname = 'pa_name';
if (!$sortorder) $sortorder = 'desc';
if($_POST['query']!=''){
$where = "WHERE `".$_POST['qtype']."` LIKE '%".$_POST['query']."%' ";
} else {
$where ='';
}
if($_POST['letter_pressed']!=''){
$where = "WHERE `".$_POST['qtype']."` LIKE '".$_POST['letter_pressed']."%' ";
}
if($_POST['letter_pressed']=='#'){
$where = "WHERE `".$_POST['qtype']."` REGEXP '[[:digit:]]' ";
}
$sort = "ORDER BY $sortname $sortorder";
if (!$page) $page = 1;
if (!$rp) $rp = 10;
$start = (($page-1) * $rp);
$limit = "LIMIT $start, $rp";
$sql = "SELECT pa_id,pa_name,pa_pd_patient_id,pa_name FROM patient_appointment $where $sort $limit";
$result = runSQL($sql);
$total = countRec('pa_id','patient_appointment',$where);
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-type: text/x-json");
$json = "";
$json .= "{\n";
$json .= "page: $page,\n";
$json .= "total: $total,\n";
$json .= "rows: [";
$rc = false;
while ($row = mysql_fetch_array($result)) {
if ($rc) $json .= ",";
$json .= "\n{";
/*$json .= "cell:['".$row['pa_name']."'";
$json .= ",'".addslashes($row['time'])."'";
$json .= ",'".addslashes($row['pa_um_id'])."'";
$json .= ",'".addslashes($row['pa_pd_patient_id'])."']";*/
$json .= "id:'".$row['pa_id']."',";
$json .= "cell:['".$row['pa_id']."','".$row['pa_name']."'";
$json .= ",'".addslashes($row['pa_pd_patient_id'])."']";
$json .= "}";
$rc = true;
}
$json .= "]\n";
$json .= "}";
echo $json;
?>
I'm guessing you're using IE browser. If so IE does not like <div id="flex1"></div> container. Change it to <table id="flex1"></table> and all should work.