i know many function to remove char in php. but i'm confused to remove this :
i want remove "," from
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$data= "['$row[keyword]', $row[jumlah]],<br>";
echo $data;}
?>
will give result :
['Smartfren', 1],
['Telkomsel', 1],
i want the output like :
['Smartfren', 1],
['Telkomsel', 1]
How to do that?
big thanks for the response.
UPDATE
based on #orangpill answer say i have printed data like :
['ABC', 6597],
['XYZ', 4479],
['PQR', 2075],
['Others', 450]
i want to make a chart, say the code of js chart have to be like :
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
based on #orangepill now my code :
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = "['$row[keyword]', $row[jumlah]]";
}
echo implode(",<br/>", $data);
?>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Presentase Sentimen Positif'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ Math.round(this.percentage) +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Nilai',
data: [
<?php while($row = mysql_fetch_array($result))
{
$data[] = "['$row[keyword]', $row[jumlah]]";
}
echo implode(",<br/>", $data); ?>
]
}]
});
});
</script>
It might make sense for you to do this by building an array and imploding it when you want to output
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = "['$row[keyword]', $row[jumlah]]";
}
echo implode(",<br/>", $data);
?>
If you are formatting for this data for consumption by javascript a better approach would be to use json_encode.
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = array($row[keyword], (int)$row[jumlah]);
}
echo "var data = ".json_encode($data).";";
?>
You can also use the substr() function:
$data = "";
while($row = mysql_fetch_array($result)) {
$data .= "['$row[keyword]', $row[jumlah]],<br>";
}
$data = substr($data, 0, -5);
echo $data;
rtrim():
$data = rtrim($data, ',');
or, in your particular example, substr:
$data = substr($data, 0, -5);
to remove the "" as well.
Related
new to this and (almost) desperate. in below code i want to set $rows1['date'][] = $data['tanggal']; data as X-Axis in highchart :
$(function () {
var chart;
$(document).ready(function() {
getAjaxData(1);
var val = location.search.split('proyek=')[1]
getAjaxData(val);
function getAjaxData(proyek){
$.getJSON("src/json/data.php", {proyek: proyek}, function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'scurve-proyek',
type: 'column'
},
title: {
text: ''
},
credits: {
enabled: false,
},
subtitle: {
text: ''
},
yAxis: {
min: 0,
max: 100,
tickInterval: 20,
title: {
text: ''
},
},
xAxis: {
type: 'datetime',
labels: {
formatter: function ( ){
return Highcharts.dateFormat('%Y-%m-%d', this.value);
},
},
},
tooltip:{
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.numberFormat(this.y, 2) +' %';
},
},
plotOptions: {
column: {
dataLabels: {
enabled: true,
format: '{point.y:,.2f}'+'%',
}
},
},
series: json
});
});
};
});
});
my data.php :
<?php
header("Content-type: application/json");
require_once "database.php";
$db = new database();
$mysqli = $db->connect();
$proyek = $_GET['proyek'];
$sql = "SELECT fren_pr FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows = array();
$rows['name'] = 'Rencana';
$rows['color'] = '#50B432';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows['data'][] = array($data['fren_pr'],);
}
$sql = "SELECT freal_pr, tanggal FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows1 = array();
$rows1['name'] = 'Realisasi';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows1['data'][] = $data['freal_pr'];
$rows1['date'][] = $data['tanggal'];
}
$rslt = array();
array_push($rslt, $rows);
array_push($rslt, $rows1);
print json_encode($rslt, JSON_NUMERIC_CHECK);
$mysqli->close();
this is my json view :
I've spent a lot of time trying to solve it but haven't found a solution until now.
Is there an error in my php code?
hope someone will be kind enough to help, Thanks in advance.
I'm trying to display a line chart with json data, but with there, $_GET from the json I have the chart doesn't appear, here's my code :
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("master/proyek/s-curve.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'scurve',
type: 'line'
},
credits: {
enabled: false
},
title: {
text: 'S-Curve Balai'
},
subtitle: {
text: ''
},
xAxis: {
categories: ['M1', 'M2', 'M3', 'M4']
},
yAxis: {
title: {
text: ''
},
plotLines: [{
value: 1,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'horizontal',
},
plotOptions: {
line: {
dataLabels: {
enabled: true,
distance: 100,
}
}
},
series: json,
});
});
});
});
and this my s-curve.php :
<?php
header("Content-type: application/json");
require_once "config/database.php";
$db = new database();
$mysqli = $db->connect();
$balai = mysqli_real_escape_string($mysqli, $_GET['balai']);
if ($balai == 'bl-1') {
$sql = "SELECT plan, actual FROM scurve1 ORDER BY id ASC";
} else if ($balai == 'bl-2') {
$sql = "SELECT plan, actual FROM scurve2 ORDER BY id ASC";
} else if ($balai == 'bl-3') {
$sql = "SELECT plan, actual FROM scurve3 ORDER BY id ASC";
}
$hasil = array();
$hasil['name'] = 'Plan';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$hasil['data'][] = $data['plan'];
}
$hasil1 = array();
$hasil1['name'] = 'Actual';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$hasil1['data'][] = $data['actual'];
}
$nilai = array();
array_push($nilai, $hasil);
array_push($nilai, $hasil1);
print json_encode($nilai, JSON_NUMERIC_CHECK);
$mysqli->close();
display my json from localhost/master/proyek/s-curve.php?balai=bl-1 :
Display Json Data
from my case above, can someone tell what error I can fix to be able to display the chart.
I am trying to add a dynamic select list to a Datatables Editor form. This is what I have tried:
var discipline_options = [];
$.getJSON('program_data/get_disciplines.php', function (data) {
$.each(data, function (index) {
discipline_options.push({
value: data[index].value,
label: data[index].text
});
});
editor.field( 'discipline_outcome.discipline_fk' ).update(discipline_options);
});
var editor = new $.fn.dataTable.Editor( {
ajax: "program_data/discipline_outcome_data.php",
table: "#discipline_outcome_table",
template: '#discipline_outcome_form',
fields: [ {
label: "Discipline:",
name: "discipline_outcome.discipline_fk",
type: "select",
placeholder: 'Choose discipline...',
placeholderDisabled: false,
placeholderValue: 0,
options: []
},...
The get_disciplines.php script is:
$data = array();
$query = "SELECT * FROM discipline";
$result = $connection->query( $query );
while ($row = mysqli_fetch_array($result)) {
$data[] = array("label"=>$row['discipline'], "value"=>$row['discipline_pk']);
}
$temp = array('disciplines[].discipline_pk'=>$data);
$json = array('options'=>$temp);
echo json_encode($json);
This script returns the following JSON, but the select list is still empty:
{
"options": {
"disciplines[].discipline_pk": [
{
"label": "Emergency Medicine",
"value": "1"
},
{
"label": "General Practice",
"value": "2"
},
{
"label": "Internal Medicine",
"value": "3"
}
]
}
}
I got it working using:
var discipline_options = [];
$.getJSON("program_data/get_disciplines.php", function(data) {
var option = {};
$.each(data, function(i,e) {
option.label = e.text;
option.value = e.id;
discipline_options.push(option);
option = {};
});
}
).done(function() {
editor.field('discipline.discipline_pk').update(discipline_options);
});
var editor = new $.fn.dataTable.Editor( {
ajax: "program_data/discipline_outcome_data.php",
table: "#discipline_outcome_table",
template: '#discipline_outcome_form',
fields: [ {
label: "Discipline:",
name: "discipline.discipline_pk",
type: "select",
placeholder: 'Choose discipline...',
placeholderDisabled: false,
placeholderValue: 0,
options: []
},...
and the get_disciplines.php:
$data = array();
$query = "SELECT * FROM discipline";
$result = $connection->query( $query );
while ($row = mysqli_fetch_array($result)) {
$data[] = array("text"=>$row['discipline'], "id"=>$row['discipline_pk']);
}
echo json_encode($data);
I'm trying to fetch data from DB for a line graph using the below code.
<?php
$dataPoints = array(
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc()) {
array("y" => 25, "label" => "Sunday"), ?>
} } else { }
);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Using the above code it gives as error as Un-expected Syntax error, expecting ) instead of ; at $dataPoints line
However if i m to remove the sql query, graph plots with static data perfectly.
Any Help is greatly appreciated..
I have to commend you for keeping PHP code and JavaScript separate. This is a very good idea. However, if you want to fetch all records from MySQL using PHP and mysqli library you do not need to have any loop. You can just fetch everything into an array and then display with json_encode() in JavaScript.
<?php
// import your mysqli connection before
$result1 = $conn->query("SELECT * FROM chart_data_column WHERE value = 'now'");
$dataPoints = $result1->fetch_all(MYSQLI_ASSOC);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?= json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<?= is short for <?php echo
You put the entire query inside the array. You need to separate them. Also, you have "chart_data_column" where the table name should be.
$dataPoints = array();
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$dataPoints[] = $row;
}
}
I am new to datatables and I am making a website search data using datatables. But mysql data is more than 10,000. When I try to search data on my web, datatables are very long displaying data. Can anyone help me, how do I get datatables to display tables faster with large data. Thank you
PHP:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "test");
$columns = array('id', 'datetime', 'temperature', 'humidity');
$query = "SELECT id, datetime, temperature, humidity FROM data WHERE ";
if($_POST["is_date_search"] == "yes")
{
$query .= 'DATE(datetime) BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(id LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= "GROUP BY DATE_FORMAT(datetime, '%d-%M-%Y-%H:%i:%s') ORDER BY 'id'";
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query );
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = "";
$sub_array[] = $row["datetime"];
$sub_array[] = $row["temperature"];
$sub_array[] = $row["humidity"];
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM data";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
?>
Javascript:
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format: "yyyy-mm-dd",
autoclose: true
});
fetch_data('no');
function fetch_data(is_date_search, start_date='', end_date='')
{
var dataTable = $('#tabel_data').DataTable({
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]],
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
filename: 'datatable'
},
],
"paging": false,
"processing" : true,
"serverSide" : true,
bFilter:false,
"ajax" : {
url:"fetch.php",
type:"POST",
data:{
is_date_search:is_date_search, start_date:start_date, end_date:end_date
},
}
});
dataTable.on('draw.dt', function () {
var info = dataTable.page.info();
dataTable.column(0, { search: 'applied', order: 'applied', page: 'applied', }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + info.start;
dataTable.cell(cell).invalidate('dom');
});
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date !='')
{
$('#tabel_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
document.getElementById('tabel').style.display = "block";
}
else
{
alert("Date Required");
}
});
});
1) use pagination how to use pagination with PHP and mysql instead of a simple query like below.
"SELECT * FROM data";
2) Dot select * because * will select unnecessary fields also instead define column name for which you want to show data
example:
select name,page,amt from data
your final query will look like
SELECT emp_id, emp_name, emp_salary FROM employee LIMIT $offset, $rec_limit;
check the link above how to use pagination with PHP and mysql