在DataTables服务器端处理脚本

时间:2016-09-29 05:08:58

标签: php jquery mysql sql datatables

我正在使用DataTables server-side processing将数据从MySQL表中提取到DataTables表中。

这是我想在我的DataTables表中运行并显示的MySQL查询:

$sql = "SELECT Client,EstimateNumber,Status,TotalEstimatedTime,CostToDateRoleTotal,ROUND((CostToDateRoleTotal/TotalEstimatedTime)*100) as PercentComplete FROM Estimates WHERE " . ($studioName != null ? "Studio = '" . $studioName. "' AND" : '') . " Status != 'Invoiced' AND Status != 'Cancelled' AND TotalEstimatedTime > 0 AND CostToDateRoleTotal > 0 ORDER BY PercentComplete DESC";

我已将DataTables服务器端处理脚本调整为:

<?php

// connection configuration
require_once 'config.php';

// db table to use
$table = 'Estimates';

// table's primary key
$primaryKey = 'EstimateNumber';

$percent_complete = "('CostToDateRoleTotal'/'TotalEstimatedTime')*100";

// 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.
$columns = array(
array('db' => 'Client', 'dt' => 0),
array('db' => 'EstimateNumber', 'dt' => 1),
array('db' => 'Status', 'dt' => 2),
array('db' => 'TotalEstimatedTime', 'dt' => 3),
array('db' => 'CostToDateRoleTotal', 'dt' => 4),
array('db' => $percent_complete, 'dt' => 4),
); // end columns array

// sql server connection information
$sql_details = array(
'user' => $currentConfig['user'],
'pass' => $currentConfig['pass'],
'db' => $currentConfig['name'],
'host' => $currentConfig['host'],
);

// DataTables helper class
require 'ssp.class.php';

function utf8ize($d) {
if (is_array($d)) {
    foreach ($d as $k => $v) {
        $d[$k] = utf8ize($v);
    }
} else if (is_string ($d)) {
    return utf8_encode($d);
}
return $d;
}


$data = SSP::complex($_GET, $sql_details, $table, $primaryKey, $columns, null, "Status != 'Invoiced' AND Status != 'Cancelled' AND TotalEstimatedTime > 0 AND CostToDateRoleTotal > 0");

echo json_encode(utf8ize($data));

此行引发错误:

$percent_complete = "('CostToDateRoleTotal'/'TotalEstimatedTime')*100";

错误是:{&#34;错误&#34;:&#34;发生SQL错误:SQLSTATE [42S22]:未找到列:1054未知列&#39;(&#39; CostToDateRoleTotal&#39; ; /&#39; TotalEstimatedTime&#39;)* 100&#39;在&#39;字段列表中&#39;}

在我上面的原始$sql查询中,我运行了此计算并将结果显示为新列$percent_complete。我试图在我的DataTables表中显示相同的结果。如何更改服务器端处理脚本以执行此计算并将其显示在新列中?

2 个答案:

答案 0 :(得分:2)

原因

ssp.class.php中定义的类SSP无法处理列别名,表达式或JOIN。

您需要更改ssp.class.php并删除所有转义列和表名称的`(反引号)字符。如果名称是保留字,您将负责自己转义列/表名。

然后替换

array('db' => $percent_complete, 'dt' => 4)

array('db' => 'ROUND((CostToDateRoleTotal/TotalEstimatedTime)*100)', 'dt' => 4)

答案 1 :(得分:-1)

我不知道SSP类如何格式化查询,但您可能想尝试添加&#34; AS percent_complete&#34;。

$percent_complete = "(CostToDateRoleTotal/TotalEstimatedTime)*100 AS percent_complete";

当您选择列时,它需要一个名称。