Hello i use the tablesorter-plugin DataTables.
I use it with serverside processing and ajax pipelining.
Here is my actual serverside script:
<?php
// Datenbank-Tabelle, die verwendet wird
$table = 'loginlogs';
// Der Primary key, der Tabelle
$primaryKey = 'id';
// Das "datetime"-Format aus der Datenbank extrahieren, nur das Datum (in das Deutsche-Format)
function getonlydate($datetime){
$exploded = explode("-", $datetime);
$explodemeagain = explode(" ", $exploded[2]);
$mergeme = $explodemeagain[0].".".$exploded[1].".".$exploded[0];
return $mergeme;
}
// Das "datetime"-Format aus der Datenbank extrahieren, nur die Uhrzeit
function getonlytime($datetime){
$exploded = explode("-", $datetime);
$explodemeagain = explode(" ", $exploded[2]);
$mergeme = $explodemeagain[1];
return $mergeme;
}
// 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' => 'ip', 'dt' => 0 ),
array(
'db' => 'status',
'dt' => 1,
'formatter' => function( $d, $row ) {
if($d == 1){
return "Erfolgreich";
}else{
return "Fehlgeschlagen";
}
}
),
array(
'db' => 'stayloggedin',
'dt' => 2,
'formatter' => function( $d, $row ) {
if($d == 1){
return "Ja";
}else{
return "Nein";
}
}
),
array(
'db' => 'date',
'dt' => 3,
'formatter' => function( $d, $row ) {
return getonlydate($d);
}
),
array(
'db' => 'date',
'dt' => 4,
'formatter' => function( $d, $row ) {
return getonlytime($d);
}
)
);
// SQL server connection information
require('../../phpfuncs/connection.php');
$sql_details = array(
'user' => $user,
'pass' => $pw,
'db' => $db,
'host' => $host
);
require('ssp.class.php');
echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
?>
Now my question is how can i do specific selects?
A specific select like:
"SELECT * FROM ".$table." WHERE userid=16"
I already searched on their website for some documentations but i can only find docs about filtering, and so on. Clientside stuff, but nothing about specific serverside possibilities.
Maybe somebody also use datatables and tablesorter and can help me out with an example?
You can use another method SSP::complex. From the comments in the code:
The difference between this method and the simple one, is that you
can apply additional where conditions to the SQL queries. These can
be in one of two forms:
'Result condition' ($whereResult) - This is applied to the result set, but not the
overall paging information query - i.e. it will not effect the number
of records that a user sees they can have access to. This should be
used when you want apply a filtering condition that the user has sent.
'All condition' ($whereAll) - This is applied to all queries that are made and
reduces the number of records that the user can access. This should be
used in conditions where you don't want the user to ever have access
to particular records (for example, restricting by a login id).
Function accepts the following arguments:
SSP::complex ($request, $conn, $table, $primaryKey, $columns, $whereResult=null, $whereAll=null)
So in order to apply the SQL query with WHERE condition, you need to change your code as follows:
echo json_encode(
SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns, null, "userid=16" )
);
Related
I have 1 row having 5 form fields. User can add/remove rows. Its repeatable row.
Now i want to store these fields into database with PDO php.
For normal values i am using this code but i am confused for repeater field.
$data = array(
'bill_no' => trim($_REQUEST['bill_no']),
'from_name' => trim($_REQUEST['from_name']),
'to_name' => trim($_REQUEST['to_name']),
'date' => trim($_REQUEST['date_bill']),
'mr_or_ms' => trim($_REQUEST['mr_or_ms']),
);
if($crud->InsertData("bill",$data)) {
header("Location: add-bill.php");
}
Insert Function:
public function InsertData($table,$fields) {
$field = array_keys($fields);
$single_field = implode(",", $field);
$val = implode("','", $fields);
try {
$query = $this->db->prepare("INSERT INTO ".$table."(".$single_field.") VALUES('".$val."')");
$query->execute();
return true;
} catch(PDOException $e) {
echo "unable to insert data";
}
}
Please help me to insert fields. Thanks
Change the names of your form fields, add [] to the end to get PHP arrays. For example change bill_no to bill_no[]. Something like this:
foreach($_REQUEST['bill_no'] as $row_number => $row_content){
$data = array(
'bill_no' => trim($_REQUEST['bill_no'][$row_number]),
'from_name' => trim($_REQUEST['from_name'][$row_number]),
'to_name' => trim($_REQUEST['to_name'][$row_number]),
'date' => trim($_REQUEST['date_bill'][$row_number]),
'mr_or_ms' => trim($_REQUEST['mr_or_ms'][$row_number]),
);
$crud->InsertData("bill",$data);
}
This assumes the browser is not mixing up the order of the fields, so maybe it's better to add unique names to the form fields when adding rows.
Also, there's no input data validation at all, please ensure you are escaping all data properly.
I did it with this method.
$total=count($_POST['description']);
for($i=0; $i<$total; $i++){
$data1 = array(
'bill_no' => trim($_POST['bill_no']),
'description' => trim($_POST['description'][$i]),
'nos' => trim($_POST['nos'][$i]),
'nos_day' => trim($_POST['nos_day'][$i]),
'pay' => trim($_POST['pay'][$i]),
'weekly_off' => trim($_POST['weekly'][$i]),
'hra' => trim($_POST['hra'][$i]),
'rs' => trim($_POST['rs'][$i]),
'ps' => trim($_POST['ps'][$i]),
);
$crud->InsertData("bill_details",$data1);
}
I am using DataTables server-side processing to pull data into a DataTables table from a MySQL table.
This is the working MySQL query I would like to run and display in my DataTables table:
$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";
I have adjusted the DataTables server-side processing script to be:
<?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));
This line is throwing an error:
$percent_complete = "('CostToDateRoleTotal'/'TotalEstimatedTime')*100";
The error is: {"error":"An SQL error occurred: SQLSTATE[42S22]: Column not found: 1054 Unknown column '('CostToDateRoleTotal'/'TotalEstimatedTime')*100' in 'field list'"}
In my original $sql query above, I ran this calculation and displayed the outcome as a new column, $percent_complete. I am trying to display those same results in my DataTables table. How can I alter my server-side processing script to perform this calculation and display it in a new column?
CAUSE
Class SSP defined in ssp.class.php cannot handle column aliases, expressions or JOINs.
SOLUTION
You need to alter ssp.class.php and remove all ` (backtick) characters that escape column and table names. You would be responsible for escaping column/table names yourself if the name is a reserved word.
Then replace
array('db' => $percent_complete, 'dt' => 4)
with
array('db' => 'ROUND((CostToDateRoleTotal/TotalEstimatedTime)*100)', 'dt' => 4)
I don't know how the SSP class formats the query but you might want to try to add "AS percent_complete".
$percent_complete = "(CostToDateRoleTotal/TotalEstimatedTime)*100 AS percent_complete";
When you SELECT a column it needs a name.
function tablesort_example_page() {
//$date2=date('m-d-Y', strtotime('t.added_date'));
// if('t.status'==1){
// $status='Active';
// }else{
// $status='Inactive';
// }
// We are going to output the results in a table with a nice header.
$header = array(
// The header gives the table the information it needs in order to make
// the query calls for ordering. TableSort uses the field information
// to know what database column to sort by.
array('data' => t('S No'), 'field' => 't.id'),
array('data' => t('Country Name'), 'field' => 't.country_name'),
array('data' => t('Status'), 'field' => 't.status'),
array('data' => t('Added Date'), 'field' => 't.added_date'),
array('data' => t('Action'), 'field' => 't.id',),
array('data' => t('Action'), '',),
);
// Using the TableSort Extender is what tells the the query object that we
// are sorting.
$limit = 10;
$query = db_select('countries', 't')->extend('TableSort')->extend('PagerDefault')->limit($limit)->orderby('id', ASC);
$query->fields('t');
// Don't forget to tell the query object how to find the header information.
$result = $query
->orderByHeader($header)
->execute();
if('$row->status'==0){
$status='Active';
} else {
$status='Inactive';
}
$rows = array();
$i=1;
foreach ($result as $row) {
//print_r($row);
// Normally we would add some nice formatting to our rows
// but for our purpose we are simply going to add our row
// to the array.
$rows[] = array(
$row->id,
$row->country_name,
$status, ----> **
here i need to execute the If condition for $status
//$row->added_date,
date('d-m-Y H:i:s', strtotime($row->added_date)),
l('edit', 'mypages/countries/'. $row->id),
l('delete', 'mypages/delete/'. $row->country_name)
);
$i++;
}
As per my database table the below are my table fields.
(id, country_name, status, added_date)
In Status there will be 0 or 1
now my Question is i need to display status
if 0 - Inactive
1 - Active
I'd suggest using a PHP ternary operator to test the value in the status field and output a string description based on that value.
$rows[] = array(
$row->id,
$row->country_name,
($row->status == 0) ? 'Inactive' : 'Active',
date('d-m-Y H:i:s', strtotime($row->added_date)),
l('edit', 'mypages/countries/'. $row->id),
l('delete', 'mypages/delete/'. $row->country_name)
);
Is it possible to get distinct values and be case insensitive? I found a couple people saying to use the aggregate function but I would keep getting errors like: exception: field path references must be prefixed with a '$' ('Classification'.
public function getDistinctValues($cid, $table, $column)
{
$mongo = new MongoClient();
$db = $mongo->leadworks;
$collection = new MongoCollection($db, $table);
//$result = $collection->distinct($column);
$result = $collection->aggregate(array(
array(
'$unwind' => $column,
),
array(
'$group' => array(
'_id' => array(
'$toLower' => array(
$column,
),
),
),
),
));
return $result;
}
This is how my document looks:
{
_id:2065565,
Date:new Date(1411732940000),
Email:"email#email.com",
Other - Industry:null,
Other - Job Duties:null,
First Name:"Test Name",
Last Name:"Test Last Name",
Title:"engineer",
Company:"Company Name Here",
Country:"UNITED STATES",
State:"MI",
Zipcode:"48071-1514",
Phone number:"777-777-7777",
Company type:"Systems integration",
}
I'm specifically trying to get distinct values for Company and ignore case.
I have two tables, User and Company. I have joining them like this:
$table = $this->getDbTable();
$select = $table->select();
$select->setIntegrityCheck( false );
$select->from( array('User'), array( 'id' => 'id',
'name' => 'User.name',
'gender' => 'User.gender',
'Company_id' => 'User.Company_id'
));
$select->join( 'Company', 'Company.id = User.Company_id',
array( 'Company_name' => 'Company.name' ,
'Company_address' => 'Company.address'
));
$rows = $table->fetchAll( $select );
It is working and giving me accurate result. Problem is that I have to mentions column names in above codes. I want to get all columns without mentioning them in above piece of code.
For example I want something like this that get all columns(But it is not providing all column values):
$table = $this->getDbTable();
$select = $table->select();
$select->setIntegrityCheck( false );
$select->from( array('User') );
$select->join( 'Company', 'Company.id = User.Company_id' );
$rows = $table->fetchAll( $select );
Thanks
Leaving away the second parameter to the from call should work: http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.columns