I am using DataTables in one of my projects in which I have to fill it with the Oracle query results. I am referring to this document.
Problem:
All the 10 columns returned by query get displayed in row 1 column 1 of the table.
Javascript
$('#inquiryForm').submit(function(){
var cnic = "data="+ $( "#cnicInd" ).val();
//alert(cnic);
$.ajax({
type: "POST",
url: "php/inquiryInd.php",
data: cnic,
success: function(datapage) {
//$("#errmsg").html(data).show();
var datacopy = [[datapage]];
prompt("Result",datacopy);
$('#dataTables-example').DataTable({
responsive: true,
"data": datacopy,
columns: [
{ title: "Policy No." },
{ title: "Client Name" },
{ title: "Gross Premium" },
{ title: "Next Due Date" },
{ title: "Commencement Date" },
{ title: "Cash Value" },
{ title: "Total Amount Paid" },
{ title: "Total Amount Due" },
{ title: "Total unconsumed Amount" },
{ title: "Status" }
]
});
}
});
$('#searchTable').show();
return false;
});
inquiryInd.php
while (($row = oci_fetch_array($stmnt)) != false) {
$result = "";
$result .= '"'.$row['PROPOSAL']."\"";
$result .= ',"'.$row['FULLNAME']."\"";
$result .= ',"'.$row['GROSSPREMIUM']."\"";
$result .= ',"'.$row['NEXTDUEDAT']."\"";
$result .= ',"'.$row['COMMENDATE']."\"";
$result .= ',"'.$row['CASH_VALUE']."\"";
$result .= ',"'.$row['TOTAL_AMOUNT_PAID']."\"";
$result .= ',"'.$row['TOTAL_AMOUNT_DUE']."\"";
$result .= ',"'.$row['TOTAL_AMOUNT_DUE']."\"";
$result .= ',"'.$row['STATUS']."\"";
//$result .= ']';
$dataset .= $result;
//Something like "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"
}
Please let me know what am I doing wrong. Any help will be highly appreciated.
Related
I create tables using datatables, and data from MySQL. I want to add string data to data in my table, for example for data in columns the temperature of each data is (C) as shown below. How do I add strings like ° C and % to my table?
PHP code:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "db_hosting");
//$columns = array('order_id', 'order_customer_name', 'order_item', 'order_value', 'order_date');
$columns = array('id', 'time', 'temperature', 'humidity');
$query = "SELECT id, DATE_FORMAT(time, '%d %M %Y %H:00') AS time, temperature, humidity FROM data WHERE ";
if($_POST["is_date_search"] == "yes")
{
$query .= 'DATE(time) 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(time, '%d-%M-%Y %H:00') ORDER BY 'time'";
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = "";
$sub_array[] = $row["time"];
$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);
?>
Table:
<table width="98%" class="table table-bordered table-striped" id="tabel_data" style="text-align:center;">
<thead >
<tr >
<th style="text-align:center;" width="8%">No.</th>
<th style="text-align:center;" width="22%">Datetime</th>
<th style="text-align:center;" width="18%">Temp (°C)</th>
<th style="text-align:center;" width="18%">Humidity (%)</th>
</tr>
</thead>
Javacript code (dataTable):
in javascript, there is a code to filter data based on date and can export table data
$(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',
title: '<h3 align ="center">Data table</h3>',
text: '<i class="fa fa-l fa-print"></i> Print',
titleAttr: 'Cetak Tabel',
messageTop: '<p align ="center">created by PDFmake</p>',
filename: 'data_table'
},
{
extend: 'pdfHtml5',
customize: function (doc) {
doc.content[1].table.widths =
Array(doc.content[1].table.body[0].length + 1).join('*').split('');
doc.defaultStyle.alignment = 'center';
doc.styles.tableHeader.alignment = 'center';
doc.content.splice(0, 1, {
text: [{
text: 'Data Table \n',
bold: true,
fontSize: 16
}, {
text: ' Created by PDFmake \n', //
bold: true,
fontSize: 11
},],
margin: [0, 0, 0, 12],
alignment: 'center'
});
},
exportOptions: {
modifier: {
selected: null
}
},
title: 'Data table',
titleAttr: 'Simpan sebagai PDF',
text: '<i class="fa fa-l fa-file-pdf-o"></i> PDF',
filename: 'data_tabel_'
}
],
"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);
//$("#tabel").show();
document.getElementById('tabel').style.display = "block";
}
else
{
alert("Both Date is Required");
}
});
});
you can create your table in JD by String:
String ="<th style="text-align:center;" width="18%">"+(variable)+"(°C)</th>"
You can wrap the content into <span>'s and do it in pure CSS:
Renderer:
columnDefs: [{
targets: [2,3],
render: function(data) {
return '<span>'+data+'</span>'
}
}]
CSS:
table.dataTable td:nth-child(3) span:after {
content: ' ℃';
color: red;
font-size: 80%;
}
table.dataTable td:nth-child(4) span:after {
content: ' %';
color: red;
font-size: 80%;
}
The benefit of this approach is that the data still is considered as numbers-
demo -> http://jsfiddle.net/1du07tfn/
I have a solution to the problem
PHP:
$data = array();
$celcius = ' °C';
$percent = ' %';
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = "";
$sub_array[] = $row["time"];
$sub_array[] = $row["temperature"].$celcius;
$sub_array[] = $row["humidity"].$percent;
$data[] = $sub_array;
}
I have the below part of code which works on my local machine but not on the server.
When I execute it on the server then am getting an error as "Uncaught SyntaxError: Unexpected token ;"
<?php
$checkValue = array();
$i= 0;
while ($row = mysql_fetch_array($searchdetails)) {
$checkValue[$i][] = $row['ID'];
$checkValue[$i][] = $row['1'];
$checkValue[$i][] = $row['2'];
$checkValue[$i][] = $row['3'];
if(#$row['4'] == "NULL" || #$row['4'] == NULL) {
$checkValue[$i][] = "NULL";
}else{
$sql = "SELECT * FROM Class WHERE ID_Class =".#$row['4'];
$data = mysql_query( $sql );
$class = mysql_fetch_assoc($data);
$checkValue[$i][] = $class['Class'];
}
if(#$row['5'] == "NULL" || #$row['5'] == NULL) {
$checkValue[$i][] = "NULL";
}else{
$sql = "SELECT * FROM Place WHERE ID_Place =".#$row['5'];
$data = mysql_query( $sql );
while($row1 = mysql_fetch_array($data)) {
$checkValue[$i][] = $row1['1'];
}
}
$i++;
}
?>
<script>
var grid;
var columns = [
{ id: "switch", name: "switch", field: "switch", formatter: imageFormatter, sortable: true },
{ id: "college", name: "college", field: "college", width: 50 },
{ id: "Number", name: "Number", field: "Number", width: 50 },
{ id: "Class", name: "Class", field: "Class",sortable: true },
{ id: "Place", name: "Place", field: "Place", width: 40 },
];
$(function () {
var MS_PER_DAY = 24 * 60 * 60 * 1000;
var data = [];
**var listdata = <?php echo json_encode($checkValue);?>;**
console.log(listdata);
for (var i = 0; i < listdata.length; i++) {
data[i] = {
switch: listdata[i][0],
college: listdata[i]['1'],
Number: listdata[i]['2'],
Strength: listdata[i]['3'],
Place: listdata[i]['4'],
};
}
})
</script>
I tried this after searching for different answers in Stackoverflow
var listdata = <?php echo json_encode($checkValue)?>;
but still it doesn't work.
What might be the issue thats stopping it here. Any help on this is much more appreciated!!
EDIT: I identified the reason, The table class has some Spanish characters in it and so it is not displaying the data. How to overcome with these characters?
I am using highchart to draw the graph, but there's a problem that I can't draw the graph when I tried to replace the URL of $.getJSON('URL', function (data)) to
$.getJSON('Highchart_getData.php', function (data) there's nothing displayed.
I choose this example
http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/stock/demo/flags-placement/
Then I want to connect my mysql data to draw the graph.
JS.javascript:
$.getJSON('Highchart_getData.php', function (data) {
var lastDate = data[data.length - 1][0], // Get year of last data point
days = 24 * 36e5; // Milliseconds in a day
// Create the chart
Highcharts.stockChart('container', {
rangeSelector: {
selected: 1
},
title: {
text: '光照量歷史圖表'
},
yAxis: {
title: {
text: '單位:Lux'
}
},
series: [{
name: '當日光照量',
data: data,
id: 'dataseries',
tooltip: {
valueDecimals: 4
}
}, {
type: 'flags',
name: 'Flags on series',
data: [{
x: lastDate - 60 * days,
title: 'On series'
}, {
x: lastDate - 30 * days,
title: 'On series'
}],
onSeries: 'dataseries',
shape: 'squarepin'
}, {
type: 'flags',
name: 'Flags on axis',
data: [{
x: lastDate - 45 * days,
title: 'On axis'
}, {
x: lastDate - 15 * days,
title: 'On axis'
}],
shape: 'squarepin'
}]
});
});
Highchart_getData.php:
<?php session_start(); ?>
<?php
$hostdb = "localhost";
$userdb = "root";
$passdb = "";
$namedb = "light_care";
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
include("mysql_connect.inc.php");
$id=$_SESSION['username'];
$today= date('Y')-2000;
$today .= date('-m-d');
$arrData = array();
if($_SESSION['username'] != null)
{
$sqlID = "select * from user where username='$id'";
$resultID = mysql_query($sqlID);
$userID=array();
if($resultID === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($resultID))
{
$userID[0]=$row["ID"];
}
for( $a=0;$a<30;$a++)
{
$date= date('Y')-2000;
$date .= date('-m-d',time()-24*60*60*$a);
//$date= date('Y-m-d',time()-24*60*60*$a);
$sql = "select * from data where user_id='$userID[0]' and data_time like
'%$date%'";
$result = mysql_query($sql);
$light=array();
//echo $date;
$count=0;
$light_sum=0;
$step_sum=0;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$lsum=array();
$ssum=array();
$Data=0;
while($row = mysql_fetch_array($result))
{
$Date=$row["data_time"];
$Data+=$row["light"];
//$light_sum+=$Data[$count];
//$DATE=$Data[$count];
$count++;
}
//echo $date;
$date= date('Y');
$date .= date('-m-d',time()-24*60*60*$a);
$DATA[0]=$date;
$DATA[1]=$Data;
array_push($arrData,$DATA);
$light_sum=0;
}
/*JSON Encode the data to retrieve the string containing the
JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
print($jsonEncodedData);
//Close the database connection
$dbhandle->close();
}
// }
?>
and the ouput is:
[["2017-07-20",0],["2017-07-19",0],["2017-07-18",562],["2017-07-17",746],["2017-07-16",0],["2017-07-15",0],["2017-07-14",0],["2017-07-13",0],["2017-07-12",0],["2017-07-11",0],["2017-07-10",0],["2017-07-09",0],["2017-07-08",0],["2017-07-07",0],["2017-07-06",0],["2017-07-05",0],["2017-07-04",0],["2017-07-03",0],["2017-07-02",0],["2017-07-01",0],["2017-06-30",0],["2017-06-29",0],["2017-06-28",0],["2017-06-27",0],["2017-06-26",0],["2017-06-25",0],["2017-06-24",0],["2017-06-23",0],["2017-06-22",0],["2017-06-21",0]]
JQ.html:
<!DOCTYPE html>
<html>
<script type="text/javascript" src="https://code.jquery.com/jquery-
3.1.1.min.js"></script>
<script type="text/javascript"
src="https://code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript"
src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<body>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
<script type="text/javascript" src="JS.js"></script>
</html>
but there's nothing being displayed :(
I have struggle for many days, but it still can't work...
Is there anyone can help me .
Thank you very much! and sorry for my poor English.
I want my capital_city autocomplete field to show only options that are related to country_name. So when choose a country in the second option field show only cities that are realted to the selected country. Thank you.
Here is my view.php:
<div class="filtering">
<form class="searchbox_1">
Country Name: <input type="text" class="search_1" name="country_name" id="country_name" />
City Name: <input type="text" class="search_1" name="capital_city" id="capital_city" />
Date from <input class="search_1" type="date" name="from_date" id="from_date"/>
Date to <input class="search_1" type="date" value = "<?php echo date('Y-m-d')?>" name="to_date" id="to_date"/>
<center><button class="submit_1" type="submit" id="LoadRecordsButton">Search</button>
<input class ="submit_1" type="reset" value="Clear fields!"></center>
</form>
</div>
<div id="countryTable"></div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#countryTable').jtable({
title: 'Country\'s',
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'country_name ASC',
selecting: true,
multiselect: true,
selectingCheckboxes: true,
selectOnRowClick: true,
actions: {
listAction: 'get_country',
createAction: 'create_country',
updateAction: 'update_country',
deleteAction: 'delete_country'
},
fields: {
country_id: {
key: true,
list: false
},
country_name: {
title: 'Country Name',
width: '11%'
},
country_code: {
title: 'Country Code',
width: '11%'
},
surface_area: {
title: 'Surface Area (m<sup>2</sup>)',
width: '13%'
},
continent_name: {
title: 'Continent Name'
},
continent: {
title: 'Continent Code',
width: '12%'
},
population: {
title: 'Population'
},
capital_city: {
title: 'Capital City'
},
record_date: {
title: 'Record Date',
type: 'date',
displayFormat: 'mm/dd/yy',
create: false,
edit: false,
sorting: false
}
},
$('#country_name').autocomplete({
source: 'list_country',
minLength: 0,
scroll: true,
autoFocus: true
}).focus(function() {
$(this).autocomplete("search", "")
.autocomplete( "widget" )
.addClass( "country_field" );
});
$('#capital_city').autocomplete({
source: 'list_city',
minLength: 0,
scroll: true,
autoFocus: true
}).focus(function() {
$(this).autocomplete("search", "")
.autocomplete( "widget" )
.addClass( "country_field" );
});
$('#LoadRecordsButton').click(function (e) {
e.preventDefault();
$('#countryTable').jtable('load', {
country_name: $('#country_name').val(),
capital_city: $('#capital_city').val(),
from_date: $('#from_date').val(),
to_date: $('#to_date').val()
});
});
$('#LoadRecordsButton').click();
});
</script>
</div>
Here is my model.php:
public function get_country_name() {
$searchTerm = filter_input(INPUT_GET, 'term');
$query = $this->db->query("SELECT DISTINCT country_name FROM country "
. "WHERE deleted=0 AND country_name LIKE '" . $searchTerm . "%' ORDER BY country_name ASC");
$row = array();
foreach ($query->result_array() as $ro) {
$row[] = $ro['country_name'];
}
echo json_encode($row);
}
public function get_city_name() {
$searchTerm = filter_input(INPUT_GET, 'term');
$query = $this->db->query("SELECT DISTINCT capital_city FROM country "
. "WHERE deleted=0 AND capital_city LIKE '" . $searchTerm . "%' ORDER BY capital_city ASC");
$row = array();
foreach ($query->result_array() as $ro) {
$row[] = $ro['capital_city'];
}
echo json_encode($row);
}
Here is my controller.php:
public function list_country(){
$this->load->model('Country_model');
$this->Country_model->get_country_name();
}
public function list_city(){
$this->load->model('Country_model');
$this->Country_model->get_city_name();
}
I have been looking for days to find a solution. Please help me. :-) .
Try adding something like this:
$('#country_name').change({
/*some code here*/
});
Then, transfer your $('#capital_city').autocomplete({}) inside, like this:
$('#country_name').change({
var country = $(this).val();
$('#capital_city').autocomplete({
source: 'list_city_' + country, /*see explanation below*/
minLength: 0,
scroll: true,
autoFocus: true
}).focus(function() {
$(this).autocomplete("search", "")
.autocomplete( "widget" )
.addClass( "country_field" );
});
});
Every time the country name is changed, the source of cities for auto-completion also changes accordingly.
For that to work, group your cities list by country when you fetch them through your model.
I was not able to test this code, and it may need some tweaks to work for you, but I hope it gives you some ideas to solve your problem. Good luck!
I have a table with 1000 records and a corresponding data history of 5 years, including events. The table structure looks like this at the moment:
id|date|reference_id|account_id|dataSet|price|title|type|description
1|2006-01-03|ID00001|1|dataSet01|44.23|Analyst opinion change|A|Upgrade by Bank from Sell to Hold
2|2006-01-03|ID00002|1|dataSet02|62.75|||
3|2006-01-03|ID00003|1|dataSet03|25.95|Dividend|D|Amount: 0.22
4|2006-01-03|ID00004|2|dataSet04|31.81|||
5|2006-01-03|ID00005|3|dataSet05|78.20|||
6|2006-02-01|ID00001|1|dataSet01|45.85|Dividend|D|Amount: 0.30
7|2006-02-01|ID00002|1|dataSet02|59.37||
8|2006-02-01|ID00003|1|dataSet03|27.59|Dividend|D|Amount: 0.26
9|2006-02-01|ID00004|2|dataSet04|34.24|||
10|2006-02-01|ID00005|3|dataSet05|83.42|||
11|2006-03-01|ID00001|1|dataSet01|45.54|Analyst opinion change|A|Upgrade by Bank from Sell to Hold
12|2006-03-01|ID00002|1|dataSet02|60.86|||
13|2006-03-01|ID00003|1|dataSet03|27.04|Downgrade by Bank from Buy to Hold
14|2006-03-01|ID00004|2|dataSet04|36.04|||
15|2006-03-01|ID00005|3|dataSet05|84.32|||
I want to render the data depending on account_id (in this case account_id = 1) to get the following JSON:
{
"data": [{
"date": "2006-01-03",
"dataSet01": "44.23",
"dataSet02": "62.75",
"dataSet03": "25.95"
}, {
"date": "2006-02-01",
"dataSet01": "45.85",
"dataSet02": "59.37",
"dataSet03": "27.59"
}, {
"date": "2006-03-01",
"dataSet01": "45.54",
"dataSet02": "60.86",
"dataSet03": "27.04"
}],
"events": [{
"dataSet01": [{
"date": "2006-01-03",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}, {
"date": "2006-02-01",
"title": "Dividend",
"text": "D",
"description": "Amount: 0.30"
}, {
"date": "2006-03-01",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}]
},{
"dataSet03": [{
"date": "2006-01-03",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}, {
"date": "2006-02-01",
"title": "Dividend",
"text": "D",
"description": "Amount: 0.30"
}, {
"date": "2006-03-01",
"title": "Analyst opinion change",
"text": "A",
"description": "Downgrade by Bank from Buy to Hold"
}]
}]
}
I'm struggling to build the json though. As of right now I'm rendering the data like this:
$query = "SELECT date, price
FROM datatable
WHERE account_id = 1
ORDER BY date ASC";
$result = mysql_query( $query );
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$data[] = $row;
}
return json_encode( $data );
Obviously this returns the json with price as label for each record value (price). How should the query look like instead to render the above json example?
$query = "SELECT *
FROM datatable
WHERE account_id = 1
ORDER BY date ASC";
$result = mysql_query( $query );
// Define temporary arrays
$data = array();
$events = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
// Assemble the data grouped by date and dataset
if ( !isset($data[$row['date']]) )
{
$data[$row['date']] = array(
'date' => $row['date'],
);
}
// Inject dataSet in $data grouped by date
if ( !isset($data[$row['date']][$row['dataSet']]) )
{
$data[$row['date']][$row['dataSet']] = $row['price'];
}
// Assemble events grouped by dataSet
if ( !isset($events[$row['dataSet']]) )
{
$events[$row['dataSet']] = array();
}
$events[$row['dataSet']][] = array(
'date' => $row['date'],
'title' => $row['title'],
'text' => $row['type'],
'description' => $row['description']
);
}
// Remove date keys
$data = array_values($data);
return json_encode(array(
'data' => $data,
'events' => $events
));