在datattables服务器端处理脚本中运行MySQL查询


Run MySQL query in DataTables server-side processing script

我正在使用DataTables服务器端处理将数据从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";

我已经调整了数据表服务器端处理脚本为:

<?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";

错误是:{"error":"An SQL error occurred: SQLSTATE[42S22]: Column not found: 1054 Unknown Column '('CostToDateRoleTotal'/'TotalEstimatedTime')*100' in 'field list'"}

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

原因

ssp.class.php中定义的SSP类不能处理列别名、表达式或join。

解决方案

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

取代

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

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

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

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

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