我正在尝试将SQL Select-Query的结果转换为DataTables可读格式的JSON文件。
现在我将结果转换为这种形式:
{
"data":[
[
"pIdWrittenHere1232131231",
"sNameWrittenHere",
"lNameWrittenHere",
"http://Some.pLogUrl.writtenHere.com/",
"incentivWrittenHere",
"https://someDetailsUrl.WrittenHere.com/
],
[
"pId2WrittenHere1232131231",
"sName2WrittenHere",
"lName2WrittenHere",
"http://Some.pLogUrl.writtenHere.com/",
"incentiv2WrittenHere",
"https://someDetailsUrl.WrittenHere.com/
]
]
}
这是我用来实际转换它们的php:
<?php
/* 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( 'pId', 'sName', 'lName', 'pLogUrl', 'incent', 'det_sUrl');
/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "id";
/* DB table to use */
$sTable = "tableName_here";
/* Database connection information */
$gaSql['user'] = "userHere";
$gaSql['password'] = "passHere";
$gaSql['db'] = "dataBaseHEre";
$gaSql['server'] = "serverHere";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/
/*
* MySQL connection
*/
$gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password'] ) or
die( 'Could not open connection to server' );
mysql_select_db( $gaSql['db'], $gaSql['link'] ) or
die( 'Could not select database '. $gaSql['db'] );
/*
* Paging
*/
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
$sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
mysql_real_escape_string( $_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] ) ]."
".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" )
{
$sOrder = "";
}
}
/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
$sWhere = "";
if ( $_GET['sSearch'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_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]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
}
}
/*
* SQL queries
* Get data to display
*/
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
/* Data set length after filtering */
$sQuery = "
SELECT FOUND_ROWS()
";
$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];
/* Total data set length */
$sQuery = "
SELECT COUNT(".$sIndexColumn.")
FROM $sTable
";
$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];
/*
* Output
*/
$output = array(
"aaData" => array()
);
while ( $aRow = mysql_fetch_array( $rResult ) )
{
$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;
}
$output = str_replace("\\/", "/", $output);
echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
?>
我必须在php中更改某些内容,以便在数据表中获取数据...
这是我的JavaScript:
$(document).ready(function() {
$('#oShopTable').DataTable( {
"bProcessing": true,
"bServerSide": true,
"ajax": "AdminPage2.php"
} );
} );
当我使用此echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
var_dump($output['data'][0]);
时,返回此处
array(6) {
[0]=> string(8) "pIdHere12312312"
[1]=> string(10) "sNameHere"
[2]=> string(17) "lNameHere"
[3]=> string(85) "https://somePLogUrlHere.com"
[4]=> string(22) "incentivHere"
[5]=> string(161) "someUrlHere"
}
答案 0 :(得分:0)
尝试类似的东西:
$query = "SELECT `id` AS `pId` FROM `table`";
// ...
$data = array('data' => mysql_fetch_assoc ($rResultFilterTotal));
$jsonData = json_encode($data);
编辑:
<?php
/* 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('pId', 'sName', 'lName', 'pLogUrl', 'incent', 'det_sUrl');
$aColumnsLabel = array('incent' => 'incentiv', 'det_sUrl' => 'detailsUrl');
/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "id";
/* DB table to use */
$sTable = "tableName_here";
/* Database connection information */
$gaSql['user'] = "userHere";
$gaSql['password'] = "passHere";
$gaSql['db'] = "dataBaseHEre";
$gaSql['server'] = "serverHere";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/
/*
* MySQL connection
*/
$gaSql['link'] = mysql_pconnect($gaSql['server'], $gaSql['user'], $gaSql['password']) or
die('Could not open connection to server');
mysql_select_db($gaSql['db'], $gaSql['link']) or
die('Could not select database ' . $gaSql['db']);
/*
* Paging
*/
$sLimit = "";
if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
$sLimit = "LIMIT " . mysql_real_escape_string($_GET['iDisplayStart']) . ", " .
mysql_real_escape_string($_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])] . "
" . mysql_real_escape_string($_GET['sSortDir_' . $i]) . ", ";
}
}
$sOrder = substr_replace($sOrder, "", -2);
if ($sOrder == "ORDER BY") {
$sOrder = "";
}
}
/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
$sWhere = "";
if ($_GET['sSearch'] != "") {
$sWhere = "WHERE (";
for ($i = 0; $i < count($aColumns); $i++) {
$sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_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] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
}
}
/*
* SQL queries
* Get data to display
*/
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . "
FROM $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query($sQuery, $gaSql['link']) or die(mysql_error());
/* Data set length after filtering */
$sQuery = "
SELECT FOUND_ROWS()
";
$rResultFilterTotal = mysql_query($sQuery, $gaSql['link']) or die(mysql_error());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];
/* Total data set length */
$sQuery = "
SELECT COUNT(" . $sIndexColumn . ")
FROM $sTable
";
$rResultTotal = mysql_query($sQuery, $gaSql['link']) or die(mysql_error());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];
/*
* Output
*/
$output = array(
"data" => array()
);
$index = 0;
while ($aRow = mysql_fetch_array($rResult)) {
$row = array();
for ($i = 0; $i < count($aColumns); $i++) {
$key = isset($aColumnsLabel[$aColumns[$i]]) ? $aColumnsLabel[$aColumns[$i]] : $aColumns[$i];
if ($aColumns[$i] == "version") {
/* Special output formatting for 'version' column */
$row[$key] = ($aRow[$aColumns[$i]] == "0") ? '-' : $aRow[$aColumns[$i]];
} else if ($aColumns[$i] != ' ') {
/* General output */
$row[$key] = $aRow[$aColumns[$i]];
}
}
$output['data'] = $row;
}
$output = str_replace("\\/", "/", $output);
echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
?>
答案 1 :(得分:-1)
所以..这是解决方案!
这里是我想要显示DataTable的页面的HTML代码(index.php):
<div class="panel-body">
<table id="oShopP" class="display">
<thead>
<tr>
<th>Price Id</th>
<th>Sync Name</th>
<th>Light Name</th>
<th>Price Logo Url</th>
<th>Incentiv</th>
<th>JTS URL</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Price Id</th>
<th>Sync Name</th>
<th>Light Name</th>
<th>Price Logo Url</th>
<th>Incentiv</th>
<th>JTS URL</th>
</tr>
</tfoot>
</table>
</div>
这里是AdPage-data.php的php:
<?php
/* Database connection start */
$servername = "localhost";
$username = "usernameHere";
$password = "passwordHere";
$dbname = "dbNameHere";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* Database connection end */
// storing request (ie, get/post) global array to a variable
$requestData= $_REQUEST;
$columns = array(
// datatable column index => database column name
0=> 'p_Id',
1=> 's_Name',
2=> 'l_Name',
3=> 'pLogo_Url',
4=> 'incentivation',
5=> 'det_jtsURL'
);
// getting total number records without any search
$sql = "SELECT p_Id, s_Name, l_Name, pLogo_Url, incentivation, det_jtsURL";
$sql.= " FROM tableNameHere";
$query=mysqli_query($conn, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql = "SELECT p_Id, s_Name, l_Name, pLogo_Url, incentivation, det_jtsURL";
$sql.=" FROM tableNameHere WHERE 1=1";
if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND ( p_Id LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR s_Name LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR l_Name LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR pLogo_Url LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR incentivation LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR det_jtsURL LIKE '".$requestData['search']['value']."%' )";
}
$query=mysqli_query($conn, $sql);
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */
$query=mysqli_query($conn, $sql);
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData[] = $row["p_Id"];
$nestedData[] = $row["s_Name"];
$nestedData[] = $row["l_Name"];
$nestedData[] = $row["pLogo_URL"];
$nestedData[] = $row["incentivation"];
$nestedData[] = $row["det_jtsURL"];
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ), // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
这里是jquery:
$(document).ready(function() {
var dataTable = $('#oShopP').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"AdPage-data.php", // json datasource
type: "post"
}
});
} );
当然index.php和AdPage-data.php必须位于同一个文件夹中,因此这段代码正好可以使用。