I'm trying to implement https://www.datatables.net/examples/data_sources/server_side.html into Typo3 (6.2LTS) with a flexible content element and templavoila. The result is a functioning but empty (No data available in table) table at the moment. I'm using the following php script:
<?php
class custom_datatable {
var $datatable; // reference to the calling object.
function custom_table1($columns,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
//do whatever you want here
//db verbindung
mysql_connect("my_host", "my_user", "my_password");
mysql_select_db("my_database");
/*
* DataTables example server-side processing script.
*
* Please note that this script is intentionally extremely simply to show how
* server-side processing can be implemented, and probably shouldn't be used as
* the basis for a large complex system. It is suitable for simple use cases as
* for learning.
*
* See http://datatables.net/usage/server-side for full details on the server-
* side processing requirements of DataTables.
*
* #license MIT - http://datatables.net/license_mit
*/
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Easy set variables
*/
// DB table to use
$table = 'my_table';
// Table's primary key
$primaryKey = 'id';
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
array( 'db' => 'Field1', 'dt' => 0 ),
array( 'db' => 'Field2', 'dt' => 1 ),
array( 'db' => 'Field3', 'dt' => 2 ),
array( 'db' => 'Field4', 'dt' => 3 ),
array( 'db' => 'Field5', 'dt' => 4 ),
array( 'db' => 'Field6', 'dt' => 5 )
);
return $columns;
}
}
?>
And get the following result in the source code:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Field1</th>
<th>Field2</th>
<th>Field3</th>
<th>Field4</th>
<th>Field5</th>
<th>Field6</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Field1</th>
<th>Field2</th>
<th>Field3</th>
<th>Field4</th>
<th>Field5</th>
<th>Field6</th>
</tr>
</tfoot>
</table>
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "Array"
} );
} );
</script>
What am I doing wrong or is missing?
in order for the server side processing to work, you must pass the right data format into it,
{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
[
"Airi",
"Satou",
"Accountant",
"Tokyo",
"28th Nov 08",
"$162,700"
],
[
"Angelica",
"Ramos",
"Chief Executive Officer (CEO)",
"London",
"9th Oct 09",
"$1,200,000"
]
]
}
then you should also check the ssp class found on github for the server side-processing query
https://github.com/DataTables/DataTables/blob/master/examples/server_side/scripts/ssp.class.php
for additional information please visit
http://legacy.datatables.net/usage/server-side
You should use it like this one:
in your datatables initialization
var your_datatable_variable_here = $('#your_datatable_id').dataTable({
responsive:true,
"bFilter": true,
"oLanguage": {
"sProcessing": "link_to_your_image_processing_gif/img/ajax-loader.gif'>"
},
"autoWidth" : true,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "your_php_file_here.php"
})
PHP FIle:
function _dataTableServerSide($iQuery,$aColumns,$dReturnType){
$iDisplayStart = $this->input->get_post('iDisplayStart', true);
$iDisplayLength = $this->input->get_post('iDisplayLength', true);
$iSortCol_0 = $this->input->get_post('iSortCol_0', true);
$iSortingCols = $this->input->get_post('iSortingCols', true);
$sSearch = $this->input->get_post('sSearch', true);
$sEcho = $this->input->get_post('sEcho', true);
$sLimit = "";
if(isset($iDisplayStart) && $iDisplayLength != '-1'){
$sLimit = "LIMIT ".$iDisplayStart.", ".$iDisplayLength; //reverse execution of limit in sql
}
if(isset($iSortCol_0)) {
$sOrder = "ORDER BY ";
for($i=0; $i<intval($iSortingCols); $i++) {
$iSortCol = $this->input->get_post('iSortCol_'.$i, true);
$bSortable = $this->input->get_post('bSortable_'.intval($iSortCol), true);
$sSortDir = $this->input->get_post('sSortDir_'.$i, true);
if($bSortable == "true") {
$sOrder .= $aColumns[intval($iSortCol)]." ".$sSortDir;
}
}
}
$sWhere = "";
if(isset($sSearch) && !empty($sSearch)) {
$sWhere = "WHERE (";
for($i=0; $i<count($aColumns); $i++) {
$bSearchable = $this->input->get_post('bSearchable_'.$i, true);
if(isset($bSearchable) && $bSearchable == 'true') {
$sWhere .= $aColumns[$i]." LIKE '%".$sSearch."%' OR ";
}
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ")";
}
for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
if ( $this->input->get_post('bSearchable_'.$i, true) == "true" && $this->input->get_post('sSearch_'.$i, true) != '' ) {
if ( $sWhere == "" ) {
$sWhere = "WHERE ";
}
else {
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".$this->input->get_post('sSearch_'.$i, true)."%' ";
}
}
switch($dReturnType) {
case 1: {
$sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns)).
" FROM (".$iQuery.") ".$sWhere." ".$sOrder." ".$sLimit;
$rResult = $this->db->query($sQuery);
$sQuery = "SELECT FOUND_ROWS() found_rows";
$iFilteredTotal = $this->db->query($sQuery)->row()->found_rows;
$sQuery = "SELECT COUNT(*) counter FROM (".$iQuery.") ";
$iTotal = $this->db->query($sQuery)->row()->counter;
} break;
case 2: {
$sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns)).
" FROM (".$iQuery.") AA ".$sWhere." "."ORDER BY gl_sub_id ASC LIMIT 1,10";//$sOrder." ".$sLimit;
$rResult = $this->db->query($sQuery);
$sQuery = "SELECT FOUND_ROWS() found_rows";
$iFilteredTotal = $this->db->query($sQuery)->row()->found_rows;
$sQuery = "SELECT COUNT(*) counter FROM (".$iQuery.") AA";
$iTotal = $this->db->query($sQuery)->row()->counter;
}
}
$output = array(
'sEcho' => intval($sEcho),
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iFilteredTotal,
'aaData' => array()
);
foreach($rResult->result_array() as $aRow) {
$row = array();
foreach($aColumns as $col) {
$row[] = $aRow[$col];
}
$output['aaData'][] = $row;
}
return $output;
}
note: this is a working example, I am using code igniter as the base framwork,and MySQL as the database, if you want to convert it to PHP, just replace the code igniter functions with the standard php $GET methods
you will need to $GET the following from the client to make it work.
$iDisplayStart = $this->input->get_post('iDisplayStart', true);
$iDisplayLength = $this->input->get_post('iDisplayLength', true);
$iSortCol_0 = $this->input->get_post('iSortCol_0', true);
$iSortingCols = $this->input->get_post('iSortingCols', true);
$sSearch = $this->input->get_post('sSearch', true);
$sEcho = $this->input->get_post('sEcho', true);
$iSortCol = $this->input->get_post('iSortCol_'.$i, true);
$bSortable = $this->input->get_post('bSortable_'.intval($iSortCol), true);
$sSortDir = $this->input->get_post('sSortDir_'.$i, true);
$bSearchable = $this->input->get_post('bSearchable_'.$i, true);
and this is where the data is processed to be passed back to client page
$output = array(
'sEcho' => intval($sEcho),
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iFilteredTotal,
'aaData' => array()
);
foreach($rResult->result_array() as $aRow) {
$row = array();
foreach($aColumns as $col) {
$row[] = $aRow[$col];
}
$output['aaData'][] = $row;
}
return $output;
Related
I'm running through some distinct user ID's (about 147 of them, retrieved from a table with many duplicates) with a foreach loop and then when retrieved, using them to retrieve more user details. I then place these details within an array in order to push them to my JavaScript.
For some reason the result that I get from the array is what seems to be an infinite loop that has quit somewhere in the process.
Here's an example:
This is the code that I am currently running:
public function payments_rt_search() {
global $wpdb;
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$threshold = intval($_POST['threshold']);
$results = $wpdb->get_results( "SELECT DISTINCT vendor_id FROM {$wpdb->prefix}wcpv_commissions WHERE order_date BETWEEN '".$date1."' AND '".$date2."'");
$past_threshold_users = [];
// echo json_encode($results);
// wp_die();
foreach ($results as $user_R) {
$total_commissions = $wpdb->get_results( "SELECT SUM(product_commission_amount) AS TotalCommissions FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id);
$total_commission = 0;
foreach($total_commissions as $total_commission_res)
{
$total_commission = $total_commission_res->TotalCommissions;
}
if ($total_commission >= $threshold)
{
$res2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id." LIMIT 1");
// echo json_encode($res2[0]);
// wp_die();
//Add user details to array
$user_deets = $res2[0];
$user_arr = array(
'vendor_id' => $user_deets->vendor_id,
'vendor_name' => $user_deets->vendor_name,
'paypal_email' => '',
'amount' => $total_commission,
'currency' => '$',
'commission_status' => $user_deets->commission_status
);
$past_threshold_users[] = $user_arr;
// echo json_encode($user_arr);
// wp_die();
}
else
{
continue;
}
echo json_encode($past_threshold_users);
}
//echo json_encode($results);
wp_die();
}
Try this code
I have move this echo json_encode($past_threshold_users); code after foreach loop.
public function payments_rt_search() {
global $wpdb;
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$threshold = intval($_POST['threshold']);
$results = $wpdb->get_results( "SELECT DISTINCT vendor_id FROM {$wpdb->prefix}wcpv_commissions WHERE order_date BETWEEN '".$date1."' AND '".$date2."'");
$past_threshold_users = [];
// echo json_encode($results);
// wp_die();
foreach ($results as $user_R) {
$total_commissions = $wpdb->get_results( "SELECT SUM(product_commission_amount) AS TotalCommissions FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id);
$total_commission = 0;
foreach($total_commissions as $total_commission_res)
{
$total_commission = $total_commission_res->TotalCommissions;
}
if ($total_commission >= $threshold)
{
$res2 = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wcpv_commissions WHERE vendor_id = ".$user_R->vendor_id." LIMIT 1");
// echo json_encode($res2[0]);
// wp_die();
//Add user details to array
$user_deets = $res2[0];
$user_arr = array(
'vendor_id' => $user_deets->vendor_id,
'vendor_name' => $user_deets->vendor_name,
'paypal_email' => '',
'amount' => $total_commission,
'currency' => '$',
'commission_status' => $user_deets->commission_status
);
$past_threshold_users[] = $user_arr;
// echo json_encode($user_arr);
// wp_die();
}
/*else
{
continue;
} */
}
echo json_encode($past_threshold_users);
//echo json_encode($results);
wp_die();
}
I am having a strange issue with my PHP / JSON data being returned by PHP. Here is my PHP:
<?php
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Easy set variables
*/
/* Array of database columns which should be read and sent back to DataTables. Use a space where
* you want to insert a non-database field (for example a counter or static image)
*/
// add your columns here!!!
$aColumns = array( 'Action', 'TimeOccurred', 'UserName', 'IPv4From', 'ShareName', 'FullFilePath', 'NewPathName', 'FromServer' );
//$aColumns = $_POST['selcolumns'];
//$aColumns = explode("-", $aColumns);
foreach ($aColumns as $col) {
file_put_contents( '../php/php-debug.txt', $col." ", FILE_APPEND );
}
$server = "";
$database = array("Database" => "");
$conn = sqlsrv_connect($server, $database);
if ($conn === false) die("<pre>".print_r(sqlsrv_errors(), true));
/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "GUID";
/* DB table to use */
$sTable = $_POST['table'];
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/
/*
* Local functions
*/
function fatal_error ( $sErrorMessage = '' ) {
header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
die( $sErrorMessage );
}
/* Ordering */
$sOrder = "";
if ( isset( $_POST['order'] ) ) {
$sOrder = "ORDER BY ";
if ( $_POST['columns'][0]['orderable'] == "true" ) {
$sOrder .= "".$aColumns[ intval( $_POST['order'][0]['column'] ) ]." ".
($_POST['order'][0]['dir']==='asc' ? 'asc' : 'desc');
}
}
/* escape function */
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
/* Filtering */
$sWhere = "";
if ( isset($_POST['search']['value']) && $_POST['search']['value'] != "" ) {
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
$sWhere .= $aColumns[$i]." LIKE '%".addslashes( $_POST['search']['value'] )."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
if ( isset($_POST['columns'][$i]) && $_POST['columns'][$i]['searchable'] == "true" && $_POST['columns'][$i]['search']['value'] != '' ) {
if ( $sWhere == "" ) {
$sWhere = "WHERE ";
}
else {
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".addslashes($_POST['columns'][$i]['search']['value'])."%' ";
}
}
/* Add the custom Date/Time filter */
if ( $sWhere == "" ) {
$sWhere = "WHERE (TimeOccurred >= "."'".$_POST['datestart']."'"." AND TimeOccurred <= "."'".$_POST['dateend']."')";
}
else {
$sWhere .= " AND (TimeOccurred >= "."'".$_POST['datestart']."'"." AND TimeOccurred <= "."'".$_POST['dateend']."')";
}
/* Paging */
$top = (isset($_POST['start']))?((int)$_POST['start']):0 ;
$limit = (isset($_POST['length']))?((int)$_POST['length'] ):5;
$sQuery = "SELECT TOP $limit ".implode(', ', $aColumns)." FROM $sTable $sWhere ".(($sWhere=="")?" WHERE ":" AND ")." $sIndexColumn NOT IN ( SELECT TOP $top $sIndexColumn FROM $sTable $sOrder ) $sOrder";
$rResult = sqlsrv_query($conn, $sQuery);
if($rResult === false){
die(sqlsrv_errors(SQLSRV_ERR_ERRORS));
}
/* Data set length after filtering */
$sQueryCnt = "SELECT * FROM $sTable $sWhere";
$rResultCnt = sqlsrv_query($conn, $sQueryCnt, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$iFilteredTotal = sqlsrv_num_rows( $rResultCnt );
/* Total data set length */
$sQuery = "SELECT COUNT(GUID) FROM $sTable";
$rResultTotal = sqlsrv_query($conn, $sQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$aResultTotal = sqlsrv_fetch_array($rResultTotal, SQLSRV_FETCH_NUMERIC);
$iTotal = $aResultTotal[0];
/* Output */
$output = array(
"draw" => intval($_POST['draw']),
"recordsTotal" => $iTotal,
"recordsFiltered" => $iFilteredTotal,
"data" => array()
);
while ( $aRow = sqlsrv_fetch_array( $rResult, SQLSRV_FETCH_ASSOC) ) {
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
$row[$aColumns[$i]] = $aRow[ $aColumns[$i] ];
}
$output['data'][] = $row;
}
echo json_encode( $output );
?>
The part of the code that has me stuck:
$aColumns = array( 'Action', 'TimeOccurred', 'UserName', 'IPv4From', 'ShareName', 'FullFilePath', 'NewPathName', 'FromServer' );
//$aColumns = $_POST['selcolumns'];
//$aColumns = explode("-", $aColumns);
foreach ($aColumns as $col) {
file_put_contents( '../php/php-debug.txt', $col." ", FILE_APPEND );
}
If I leave my code as is and run through the process I get the data back as expected and everything works. I also get this output in my php-debug.txt:
Action TimeOccurred UserName IPv4From ShareName FullFilePath NewPathName FromServer
If I modify these lines of my code to this:
//$aColumns = array( 'Action', 'TimeOccurred', 'UserName', 'IPv4From', 'ShareName', 'FullFilePath', 'NewPathName', 'FromServer' );
$aColumns = $_POST['selcolumns'];
$aColumns = explode("-", $aColumns);
foreach ($aColumns as $col) {
file_put_contents( '../php/php-debug.txt', $col." ", FILE_APPEND );
}
I do not get the data back as expected. I get a warning stating invalid JSON response and in my php-debug.txt I get this content:
Action TimeOccurred UserName IPv4From ShareName FullFilePath NewPathName FromServer
It is driving me bonkers that the array has the same values either way and yet it doesn't work. There is an extra space on the end of the php-debug.txt the 2nd time around, not sure where that comes from or if it is the problem.
Hopefully someone can point me in the right direction.
I figured out the problem. For some reason there is an extra element being added to my array, but its an empty element so when I print there is nothing there. I added this to my code array_pop($aColumns); and for now that resolved the problem. Its kind of a dirty workout though, and I can't help but think that eventually there will come a scenario where the last element isn't blank and its something I need. Would love to figure out a cleaner solution.
I am using jQuery Datatables to populate my data. I am using the server side method which I need coz I am fetching hundred thousand records. However I don't know how to add a custom field. For example
|Action|
________
http://localhost/qms/public/customer/1/edit
Which the 1 should be the ID
Because on the datatables, you only declaring column tables that you need so I don't know how to add a custom one.
I currently have this:
I need to put action column to edit those customers. I am using Laravel 5.1
HTML View:
<table id="CustomerList" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th colspan="7"> <center>Customer Information<center></th>
<!-- <th colspan="2"> <center>Actions<center></th> -->
</tr>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Phone Number</th>
<th>Country</th>
<th>Postcode</th>
<!-- <th>Edit</th>
<th>Delete</th> -->
</tr>
</thead>
<tbody>
</tbody>
</table>
Ajax:
<script type="text/javascript">
$(document).ready(function() {
$.fn.dataTable.ext.legacy.ajax = true;
$('#CustomerList').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "api/customer/all",
"paging" : true,
"searching" : true,
"ordering" : true,
} );
var tt = new $.fn.dataTable.TableTools( $('#CustomerList').DataTable() );
$( tt.fnContainer() ).insertBefore('div.dataTables_wrapper');
});
</script>
Controller:
public function apiGetCustomers()
{
/*=================================================================*/
/*
* Script: DataTables server-side script for PHP and PostgreSQL
* Copyright: 2010 - Allan Jardine
* License: GPL v2 or BSD (3-point)
*/
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Easy set variables
*/
/* Array of database columns which should be read and sent back to DataTables. Use a space where
* you want to insert a non-database field (for example a counter or static image)
*/
$aColumns = array('id', 'firstname', 'lastname', 'gender', 'phone_num', 'country', 'postcode' );
/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "phone_num";
/* DB table to use */
$sTable = "customers";
/* Database connection information */
$gaSql['user'] = "postgres";
$gaSql['password'] = "postgres";
$gaSql['db'] = "qms";
$gaSql['server'] = "localhost";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/
/*
* DB connection
*/
$gaSql['link'] = pg_connect(
" host=".$gaSql['server'].
" dbname=".$gaSql['db'].
" user=".$gaSql['user'].
" password=".$gaSql['password']
) or die('Could not connect: ' . pg_last_error());
/*
* Paging
*/
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
$sLimit = "LIMIT ".intval( $_GET['iDisplayLength'] )." OFFSET ".
intval( $_GET['iDisplayStart'] );
}
/*
* Ordering
*/
if ( isset( $_GET['iSortCol_0'] ) )
{
$sOrder = "ORDER BY ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
{
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
{
$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
".($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc').", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" )
{
$sOrder = "";
}
}
/*
* Filtering
* NOTE This assumes that the field that is being searched on is a string typed field (ie. one
* on which ILIKE can be used). Boolean fields etc will need a modification here.
*/
$sWhere = "";
if ( $_GET['sSearch'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $_GET['bSearchable_'.$i] == "true" )
{
if($aColumns[$i] != 'id') // Exclude ID for filtering
{
$sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string( $_GET['sSearch'] )."%' OR ";
}
}
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ")";
}
/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
{
if ( $sWhere == "" )
{
$sWhere = "WHERE ";
}
else
{
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string($_GET['sSearch_'.$i])."%' ";
}
}
$sQuery = "
SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
$sQuery = "
SELECT $sIndexColumn
FROM $sTable
";
$rResultTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
$iTotal = pg_num_rows($rResultTotal);
pg_free_result( $rResultTotal );
if ( $sWhere != "" )
{
$sQuery = "
SELECT $sIndexColumn
FROM $sTable
$sWhere
";
$rResultFilterTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
$iFilteredTotal = pg_num_rows($rResultFilterTotal);
pg_free_result( $rResultFilterTotal );
}
else
{
$iFilteredTotal = $iTotal;
}
/*
* Output
*/
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
while ( $aRow = pg_fetch_array($rResult, null, PGSQL_ASSOC) )
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == "version" )
{
/* Special output formatting for 'version' column */
$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
}
else if ( $aColumns[$i] != ' ' )
{
/* General output */
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['aaData'][] = $row;
}
echo json_encode( $output );
// Free resultset
pg_free_result( $rResult );
// Closing connection
pg_close( $gaSql['link'] );
}
Add headers for the custom fields, as you have above <th>Edit</th><th>Delete</th>
Use column rendering to add the content of the custom fields. Since you are using an "array of arrays" as datasource, you must do it this way :
small demonstration -> http://jsfiddle.net/pqgynvys/
var table = $('#example').DataTable({
data : data.data,
columns : [
null,
null,
null,
null,
null,
null,
null,
{ render : function() {
return '<button>edit</button>'
}
},
{ render : function() {
return '<button>delete</button>'
}
}
]
})
SOLUTION
In HTML add one column in the table header for Action.
In DataTables initialization options add columnDefs to target that 8th column ("targets": 7, zero-based index) and use render option to produce content for that column.
In the render function, you can use row variable to access the data for the row. Since you're returning array of arrays in your PHP script, you can access your ID by using row[0] (1st column, zero-based index).
var table = $('#CustomerList').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "api/customer/all"
"columnDefs": [
{
"targets": 7,
"render": function(data, type, row, meta){
return 'Edit';
}
}
]
});
DEMO
See this jsFiddle for code and demonstration.
I'm trying to populate a datatable with a server side PHP script which echoes the data from a postgres table (~75K rows). I followed the steps given in the datatable page and implemented it, but the table doesn't show any data. This is what I have so long:
table definition in a jsp file:
<table id="myTable" class="table table-striped" width="100%">
<thead>
<tr>
<th>idpersona</th>
<th>primerapellido</th>
<th>primernombre</th>
<th>numeroidentificacion</th>
<th>fechanacimiento</th>
</tr>
</thead>
<tfoot>
<tr>
<th>idpersona</th>
<th>primerapellido</th>
<th>primernombre</th>
<th>numeroidentificacion</th>
<th>fechanacimiento</th>
</tr>
</tfoot>
</table>
Here is my function to initialise the table. I tried for hours (I'm a newbie programmer) to find the right folder where I must place the PHP file. Right now it is in the htdocs folder of my apache server (so I can access it from /localhost/tablabd.php). Is this the right way to do it?
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#myTable').dataTable( {
"Processing": true,
"ServerSide": true,
"sAjaxSource": "http://localhost/tablabd.php"
} );
} );
</script>
And finally the PHP script. When I type localhost/tablabd.php in my browser, all the data is fetched correctly. But when I execute my Java project, it doesn't show anything in the table 'myTable'.
<?php
/*
* Script: DataTables server-side script for PHP and PostgreSQL
* Copyright: 2010 - Allan Jardine
* License: GPL v2 or BSD (3-point)
*/
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Easy set variables
*/
/* Array of database columns which should be read and sent back to DataTables. Use a space where
* you want to insert a non-database field (for example a counter or static image)
*/
$aColumns = array("idpersona", "primerapellido","primernombre", "numeroidentificacion", "fechanacimiento");
/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = '"idpersona"';
/* DB table to use */
$sTable = '"tpersonas"';
/* Database connection information */
$gaSql['user'] = "postgres";
$gaSql['password'] = "******";
$gaSql['db'] = "sisben";
$gaSql['server'] = "localhost";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/
/*
* DB connection
*/
$gaSql['link'] = pg_connect(
" host=".$gaSql['server'].
" dbname=".$gaSql['db'].
" user=".$gaSql['user'].
" password=".$gaSql['password']
) or die('Could not connect: ' . pg_last_error());
/*
* Paging
*/
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
$sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] )." OFFSET ".
intval( $_GET['iDisplayLength'] );
}
/*
* Ordering
*/
if ( isset( $_GET['iSortCol_0'] ) )
{
$sOrder = "ORDER BY ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
{
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
{
$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
".($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc').", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" )
{
$sOrder = "";
}
}
/*
* Filtering
* NOTE This assumes that the field that is being searched on is a string typed field (ie. one
* on which ILIKE can be used). Boolean fields etc will need a modification here.
*/
$sWhere = "";
if ( $_GET['sSearch'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $_GET['bSearchable_'.$i] == "true" )
{
$sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string( $_GET['sSearch'] )."%' OR ";
}
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ")";
}
/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
{
if ( $sWhere == "" )
{
$sWhere = "WHERE ";
}
else
{
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string($_GET['sSearch_'.$i])."%' ";
}
}
$sQuery = "
SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
$sQuery = "
SELECT $sIndexColumn
FROM $sTable
";
$rResultTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
$iTotal = pg_num_rows($rResultTotal);
pg_free_result( $rResultTotal );
if ( $sWhere != "" )
{
$sQuery = "
SELECT $sIndexColumn
FROM $sTable
$sWhere
";
$rResultFilterTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
$iFilteredTotal = pg_num_rows($rResultFilterTotal);
pg_free_result( $rResultFilterTotal );
}
else
{
$iFilteredTotal = $iTotal;
}
/*
* Output
*/
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
while ( $aRow = pg_fetch_array($rResult, null, PGSQL_ASSOC) )
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == 'idpersona' )
{
/* Special output formatting for 'ID' column */
$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
}
else if ( $aColumns[$i] != ' ' )
{
/* General output */
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['aaData'][] = $row;
}
echo json_encode( $output );
// Free resultset
pg_free_result( $rResult );
// Closing connection
pg_close( $gaSql['link'] );
?>
and a sample of the output of the script in the broswer: maybe I'm missing a column mapping somewhere?
{"sEcho":0,"iTotalRecords":74047,"iTotalDisplayRecords":74047,"aaData":[["e71657b3-a7f5-4a10-bc43-d0edbeb5cdab","PEREZ","ABDON","4299249","1947-07-10 00:00:00"],["796db2d4-fee3-4cca-ae06-429a2ea6c5af","TORREZ","MARIA","24240762","1951-09-17 00:00:00"]]}
Here is the info Firebug shows when I access the page on my application which contains the table:
_ 1440905636814
columns[0][data] 0
columns[0][name]
columns[0][orderable] true
columns[0][search][regex] false
columns[0][search][value]
columns[0][searchable] true
columns[1][data] 1
columns[1][name]
columns[1][orderable] true
columns[1][search][regex] false
columns[1][search][value]
columns[1][searchable] true
columns[2][data] 2
columns[2][name]
columns[2][orderable] true
columns[2][search][regex] false
columns[2][search][value]
columns[2][searchable] true
columns[3][data] 3
columns[3][name]
columns[3][orderable] true
columns[3][search][regex] false
columns[3][search][value]
columns[3][searchable] true
columns[4][data] 4
columns[4][name]
columns[4][orderable] true
columns[4][search][regex] false
columns[4][search][value]
columns[4][searchable] true
draw 1
length 20
order[0][column] 0
order[0][dir] asc
search[regex] false
search[value]
start 0
Thanks in advance.
SOLUTION
Correct option names are bProcessing and bServerSide. Your DataTables initialization code should be:
$('#myTable').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/tablabd.php"
});
NOTES
I have changed URL to /tablabd.php because if your HTML and PHP are on different domain, Ajax calls may fail unless you allow cross-domain requests. Make sure you have HTML and PHP on the same domain.
I try to make query in Codeigniter via Active Records:
if (isset($data['where']['and'])) {
$this->db->where($data['where']['and']);
}
if (isset($data['where']['or'])) {
$this->db->or_where_in('idSpec', $data['where']['or']);
}
I want to get:
WHERE name = 1 AND (idSpec = 2 OR idSpec = 3 OR idSpec = 4);
But now I get:
WHERE name = 1 OR idSpec = 2 OR idSpec = 3 OR idSpec = 4;
Use below code.
if (isset($data['where']['and'])) {
$this->db->where($data['where']['and']);
}
if (isset($data['where']['or'])) {
$this->db->where("(idSpec = 2 OR idSpec = 3 OR idSpec = 4;)", NULL, FALSE);
}
I assume your $data['where']['or'] contains some ids.
This may help you.
if (isset($data['where']['or']))
{
$or_conditions='(idSpec ='.implode(' OR idSpec = ',$data['where']['or']).')';
$this->db->where($or_conditions);//if this produce error use bellow one
//$this->db->where($or_conditions,'',false);
}
This is the basic method to select data from database I'm using well for a long time..
/**
* Le wild function to make a life better.
* Doing abrakadabra
*
* #param $table
* #param bool $selector
* #param string $order
* #param bool $start
* #param bool $limit
* #param $return
*
* #return mixed
*/
public function _getCustomTableData($table, $selector = FALSE, $order = 'id DESC', $start = FALSE, $limit = FALSE, $return = FALSE, $group_by = FALSE)
{
$query = $return ? $this->db->select($return) : $this->db->select('*');
if ( $selector ) {
if ( isset($selector['mixed_selection']) && $selector['mixed_selection'] == TRUE ) {
$query = $this->db->where($selector['mixed_selection']);
} else {
foreach ( $selector as $select_array ):
$query = $this->db->where($select_array);
endforeach;
}
}
if ( $group_by ) {
$query = $this->db->group_by($group_by);
}
$query = $this->db->order_by($order);
if ( $start && $limit ) {
$query = $this->db->limit($limit, $start);
}
if ( ! $start && $limit ) {
$query = $this->db->limit($limit);
}
// proceed
$query = $this->db->get($table);
if ( $limit == TRUE && $limit == 1 ) {
$query = $query->row_array();
if ( $return ) {
return $query[$return];
} else {
return $query;
}
} else {
$query = $query->result_array();
return $query;
}
}
and query looks like:
$this->_getCustomTableData('table', array(array('selector' => '1', 'time >=' => time())), 'id DESC', FALSE, 1, 'id');
it's like:
SELECT 'id' FROM `table` WHERE `selector` = 1 AND `time` >= 1472582... ORDER BY id DESC LIMIT 1
or you can use "mixed selection"
$this->_getCustomTableData('table', array('mixed_selection' => 'selector = 1 AND time >= 1472582...'), 'id DESC', FALSE, 1, 'id');
and the result will be the same. I have wrote this method when I was beginner with CI and it helped me a lot :)