GithubHelp home page GithubHelp logo

n1crack / datatables Goto Github PK

View Code? Open in Web Editor NEW
262.0 22.0 89.0 220 KB

Simplify your Datatables server-side processing effortlessly using our lightning-fast PHP library, streamlining your workflow seamlessly.

Home Page: https://datatables.ozdemir.be/

License: MIT License

PHP 100.00%
datatables datatables-library php-library sqlite mysql php datatables-serverside laravel codeigniter prestashop

datatables's Introduction

Datatables library for PHP

Latest Stable Version PHP Composer license

Simplify your Datatables server-side processing effortlessly using our lightning-fast PHP library, streamlining your workflow seamlessly. Live Demo

Features

Installation

NOTE: version 2.0+ requires php 7.1.3+ (php supported versions)

The recommended way to install the library is with Composer

If you haven't started using composer, I highly recommend you to use it.

Put a file named composer.json at the root of your project, containing this information:

{
    "require": {
       "ozdemir/datatables": "2.*"
    }
}

And then run:

composer install

Or just run :

composer require ozdemir/datatables

Add the autoloader to your project:

    <?php

    require_once 'vendor/autoload.php';

You're now ready to begin using the Datatables php library.

    <?php
    require_once 'vendor/autoload.php';

    use Ozdemir\Datatables\Datatables;
    use Ozdemir\Datatables\DB\MySQL;

    $config = [ 'host'     => 'localhost',
                'port'     => '3306',
                'username' => 'homestead',
                'password' => 'secret',
                'database' => 'sakila' ];

    $dt = new Datatables( new MySQL($config) );

    $dt->query('Select film_id, title, description from film');

    echo $dt->generate();

If you are using a php framework such as codeigniter or laravel, you can use the relevant database adapter.

// Codeigniter 4 Example

<?php

namespace App\Controllers;

use Config\Database;
use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\Codeigniter4Adapter;

class Home extends BaseController
{
    public function index()
    {
        return view('index');
    }

    public function ajax()
    {
        // CI 4 builder class
        $db = Database::connect();

        $builder = $db->table('Track');
        $builder->select('TrackId, Name, UnitPrice');

        // Datatables Php Library
        $datatables = new Datatables(new Codeigniter4Adapter);

        // using CI4 Builder
        $datatables->query($builder);

        // alternatively plain sql
        // $datatables->query('Select TrackId, Name, UnitPrice from Track');

        return $this->response->setJSON($datatables->generate()->toJson());
    }
}
// Laravel Example

<?php
// routes/web.php 

use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\LaravelAdapter;

Route::get('/ajax/laravel', function () {

    $dt = new Datatables(new LaravelAdapter);

    $dt->query(
      Track::query()
          ->select([
              'TrackId',
              'Track.Name',
              'Title as Album',
              'MediaType.Name as MediaType',
              'UnitPrice',
              'Milliseconds',
              'Bytes',
          ])
          ->join('Album', 'Album.AlbumId', 'Track.AlbumId')
          ->join('MediaType', 'MediaType.MediaTypeId', 'Track.MediaTypeId')
    ); // same as the previous example, sql statement can be used.

    return $dt->generate();
});

Methods

This is the list of available public methods.

query($query) required

  • sets the sql query

generate() required

  • runs the queries and build outputs
  • returns the output as json
  • same as generate()->toJson()

toJson()

  • returns the output as json
  • should be called after generate()

toArray()

  • returns the output as array
  • should be called after generate()

add($column, function( $row ){})

  • adds extra columns for custom usage

edit($column, function($row){})

  • allows column editing

filter($column, function(){})

  • allows custom filtering
  • it has the methods below
    • escape($value)
    • searchValue()
    • defaultFilter()
    • between($low, $high)
    • whereIn($array)
    • greaterThan($value)
    • lessThan($value)

hide($columns)

  • removes the column from output
  • It is useful when you only need to use the data in add() or edit() methods.

setDistinctResponseFrom($column)

  • executes the query with the given column name and adds the returned data to the output with the distinctData key.

setDistinctResponse($output)

  • adds the given data to the output with the distinctData key.

getColumns()

  • returns column names (for dev purpose)

getQuery()

  • returns the sql query string that is created by the library (for dev purpose)

Example

    <?php
    require_once 'vendor/autoload.php';

    use Ozdemir\Datatables\Datatables;
    use Ozdemir\Datatables\DB\SQLite;

    $path = __DIR__ . '/../path/to/database.db';
    $dt = new Datatables( new SQLite($path) );

    $dt->query('Select id, name, email, age, address, plevel from users');

    $dt->edit('id', function($data){
        // return a link.
        return "<a href='user.php?id=" . $data['id'] . "'>edit</a>";
    });

    $dt->edit('email', function($data){
        // masks email : [email protected] => m***@mail.com
        return preg_replace('/(?<=.).(?=.*@)/u','*', $data['email']);
    });

    $dt->edit('address', function($data){
        // checks user access.
        $current_user_plevel = 4;
        if ($current_user_plevel > 2 && $current_user_plevel > $data['plevel']) {
            return $data['address'];
        }

        return 'you are not authorized to view this column';
    });
    
    $dt->hide('plevel'); // hides 'plevel' column from the output

    $dt->add('action', function($data){
        // returns a link in a new column
        return "<a href='user.php?id=" . $data['id'] . "'>edit</a>";
    });

    $dt->filter('age', function (){
        // applies custom filtering.
        return $this->between(15, 30);
    });

    echo $dt->generate()->toJson(); // same as 'echo $dt->generate()';

Road Map

  • better test suites for each class
  • improve integrations for php frameworks

Requirements

Composer
DataTables > 1.10
PHP > 7.1.3

License

Copyright (c) 2015 Yusuf ÖZDEMİR, released under the MIT license

If you like the library

Buy Me A Coffee

datatables's People

Contributors

andrejflorjancic avatar djpa3k avatar gijsdev avatar kalider avatar lelinhtinh avatar lequer avatar n1crack avatar ozdemiremrah avatar peter279k avatar titnouk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

datatables's Issues

Query with subselect columns error

If query has subselect of any kind, function setcolumns return empty string. I found a solution:

private function setcolumns($query)
{
$query = preg_replace("/(([^()]|(?R))*)/i", "", $query);
.....
}

Datatable File Displays Cache Header

ajax.php

<?php
    require_once('config/config.php');

    require_once 'vendor/autoload.php';

    use Ozdemir\Datatables\Datatables;
    use Ozdemir\Datatables\DB\MySQL;

    $dt = new Datatables( new MySQL([ 'host'     => DB_HOST,
                'port'     => DB_PORT,
                'username' => DB_USER,
                'password' => DB_PASS,
                'database' => DB_NAME ]));

 $dt->query('Select role_id, role_type from user_roles');

   echo $dt->generate()->toJson(); // same as 'echo $dt->generate()';
    ?>

index.php


    <!DOCTYPE html>
    <html>
    <head>
    	<title></title>
    	<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css
">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.dataTables.min.css

">
    </head>
    <body>
    	<table border="0" class="display" id="example" width="100%">
    <thead>
    <tr>
        <th width="50%">role_id</th>
        <th width="50%">role_type</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>loading...</td>
    </tr>
    </tbody>
</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>

<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>

    <script type="text/javascript">
$(document).ready(function () {
  $('#example').dataTable({
      "serverSide": true,
      "responsive": true,
      "ajax": "ajax.php"
  });
});
    </script>

    </body>
    </html>

Response in xampp
image

Response in Ampps on php 7.1

Fatal error: Uncaught PDOException: could not find driver in C:\Program Files (x86)\Ampps\www\test\vendor\ozdemir\datatables\src\DB\MySQL.php:45 Stack trace: #0 C:\Program Files (x86)\Ampps\www\test\vendor\ozdemir\datatables\src\DB\MySQL.php(45): PDO->__construct('mysql:host=loca...', 'root', '') #1 C:\Program Files (x86)\Ampps\www\test\vendor\ozdemir\datatables\src\Datatables.php(59): Ozdemir\Datatables\DB\MySQL->connect() #2 C:\Program Files (x86)\Ampps\www\test\ajax.php(29): Ozdemir\Datatables\Datatables->__construct(Object(Ozdemir\Datatables\DB\MySQL)) #3 {main} thrown in C:\Program Files (x86)\Ampps\www\test\vendor\ozdemir\datatables\src\DB\MySQL.php on line 45

Codeigniter - Order by Columns not working, ozdemir/datatables:^2.2

I'm using ozdemirdatatables in codeigniter 3.1.6, try ordering by column but not working...

SELECT pelapor.nik, pelapor.nama_lengkap, kategori.kategori, laporan.id, laporan.isi_laporan, laporan.lokasi_kejadian, laporan.latlng, laporan.status, laporan.disposisi, opd.nama_opd, laporan.tgl_input FROM laporan join kategori on kategori.id=laporan.kategori join pelapor on pelapor.nik=laporan.nik left join opd on opd.id=laporan.disposisi order by laporan.status asc

Thanks' :D

how to modify request data

I'm using this library for SQLite. And I had a problem with pivot tables that's why I just hard-coded what would usually be written in query.

foreach($data as $row){ 
       $flat_data[$row['some_id']] = [ ... ]
}

Now as you might expect, the problem now would be the limit. Because the limit is only applied to the query, it will no longer be the same as the number of records actually being returned. It would probably mess up the pagination as well. So I was thinking of modifying the request data coming from datatables on the client side. Tried the suggestion here but it doesn't really work. It still honors the limit selected on the client side.

public function getData(Request $request)
{
  $request->merge(['length' => 1000]);
} 

Any ideas?

trying to upgrade to newest version

I was still using the old version of you api. but need to update due to "out of memory" errors due to the count() function in mysql.php. However I get errors...

Notice: Undefined offset: 7 in /home/eosdac/eosdac-token-explorer/api/vendor2/ozdemir/datatables/src/ColumnCollection.php on line 156

Notice: Undefined offset: 8 in /home/eosdac/eosdac-token-explorer/api/vendor2/ozdemir/datatables/src/ColumnCollection.php on line 156

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 't.account_action_seq'; this is incompatible with sql_mode=only_full_group_by in /home/eosdac/eosdac-token-explorer/api/vendor2/ozdemir/datatables/src/DB/MySQL.php:70 Stack trace: #0 /home/eosdac/eosdac-token-explorer/api/vendor2/ozdemir/datatables/src/DB/MySQL.php(70): PDOStatement->execute(Array) #1 /home/eosdac/eosdac-token-explorer/api/vendor2/ozdemir/datatables/src/Datatables.php(163): Ozdemir\Datatables\DB\MySQL->count(Object(Ozdemir\Datatables\Query)) #2 /home/eosdac/eosdac-token-explorer/api/vendor2/ozdemir/datatables/src/Datatables.php(142): Ozdemir\Datatables\Datatables->setResponseData() #3 /home/eosdac/eosdac-token-explorer/api/explorer_table_api2.php(46): Ozdemir\Datatables\Datatables->generate() #4 {main} thrown in /home/eosdac/eosdac-token-explorer/api/vendor2/ozdemir/datatables/src/DB/MySQL.php on line 70

same error as screenshot:
image

my request:
https://explorer.eosdac.io/explorer_table_api2.php?get=transfers&draw=1&columns[0][data]=account_action_seq&columns[0][name]=&columns[0][searchable]=false&columns[0][orderable]=false&columns[0][search][value]=&columns[1][data]=_from&columns[1][name]=&columns[1][searchable]=true&columns[1][orderable]=false&columns[1][search][value]=&columns[2][data]=_to&columns[2][name]=&columns[2][searchable]=true&columns[2][orderable]=false&columns[2][search][value]=&columns[3][data]=_quantity&columns[3][name]=&columns[3][searchable]=false&columns[3][orderable]=false&columns[3][search][value]=&columns[4][data]=_symbol&columns[4][name]=&columns[4][searchable]=false&columns[4][orderable]=false&columns[4][search][value]=&columns[5][data]=block_time&columns[5][name]=&columns[5][searchable]=false&columns[5][orderable]=false&columns[5][search][value]=&columns[6][data]=txid&columns[6][name]=&columns[6][searchable]=true&columns[6][orderable]=false&columns[6][search][value]=&order[0][column]=0&order[0][dir]=desc&start=20&length=20&search[value]=

Column name on return

Is it possible to change the result where each column is numbered for the names? Example:
Currently the result is this

[
 ...
[ 
0: 'Mary',
1: 25
]
...
 ]

I would like to see it like this

[
 ...
[ 
'name': 'Mary',
'age': 25
]
...
 ]

Encoding arabic character issue

I got issue with arabic encoding. Its fine using native server side by datatable, but read as strange character when using your repo. please help.
وقالت زينب� : أنا .... وأنا قَاد�مَةٌ من مَال�يْز�يَا
image

Multiple word search

Try this version of function filterglobal

$searchinput = $this->input('search')['value'];
$allcolumns = $this->input('columns');

if ($searchinput == '')
{
return null;
}

$search = [];
$searchinput = preg_replace("/\W+/", " ", $searchinput);
foreach (explode(' ',$searchinput) as $word) {
$lookfor = [];
foreach ($this->columns as $key => $column) {
if ($allcolumns[$key]['searchable'] == 'true') {
$lookfor[] = $column . " LIKE " . $this->db->escape($word) . "";
}
}
$search[] = "(".implode(" OR ", $lookfor) . ")";
}

return implode(" AND ", $search);

Searches for all the words in a row.

Default order

Can you change orderby() default part . Please check if query has order inside, than use this order as default, not first column.

if ( ! is_array($dtorders))
{
return >>query has order by<<?"":$orders . $this->columns[0] . " asc"; // default
}

I have solution, can I send you by mail?

undefined offset error

got this error with a simple select * from table

Notice: Undefined offset: 2 in /var/www/html/explorer/vendor/ozdemir/datatables/src/Datatables.php on line 220

Notice: Undefined index: ASC in /var/www/html/explorer/vendor/ozdemir/datatables/src/Datatables.php on line 220

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 10 OFFSET 0' at line 1 in /var/www/html/explorer/vendor/ozdemir/datatables/src/DB/MySQL.php:38 Stack trace: #0 /var/www/html/explorer/vendor/ozdemir/datatables/src/DB/MySQL.php(38): PDOStatement->execute(Array) #1 /var/www/html/explorer/vendor/ozdemir/datatables/src/Datatables.php(73): Ozdemir\Datatables\DB\MySQL->query('Select * from (...') #2 /var/www/html/explorer/vendor/ozdemir/datatables/src/Datatables.php(228): Ozdemir\Datatables\Datatables->execute() #3 /var/www/html/explorer/explorer_api2.php(55): Ozdemir\Datatables\Datatables->generate() #4 {main} thrown in /var/www/html/explorer/vendor/ozdemir/datatables/src/DB/MySQL.php on line 38

Acute accent problem

Filter string value is cleaned by filterglobal(),
example: ženšen ( ginsen)

$searchinput = 'ženšen';
$searchinput = preg_replace("/\W+/", " ", $searchinput);
$searchinput = 'enen';

This wokrs fien for Czech language:

$searchinput = 'ženšen';
$searchinput = preg_replace("/[^a-zA-Zá-žÁ-Ž0-9 ]+/", "", $searchinput);
$searchinput = 'ženšen';

Search Case Insensitive

Love this project! For the life of me I cannot figure out how to search case insensitive. It will only search case sensitive. Many thanks in advance.

Newbie Issues...

Thank you for posting this git, your a life saver. I'm fairly new at using php, and am running into a few issues.

I didn't use composer, instead just copied over the required documents. I also created the "composer.json" file and put it in the root folder.

My questions/issues:

  1. What is "namespace Ozdemir\Datatables\DB"? I can't find these folders.
  2. In the ajax.php file it calls for:
    use Ozdemir\Datatables\Datatables;
    use Ozdemir\Datatables\DB\MySQL;
    What are these doing? If I am calling my own database, do these change?

Thanks!

Count request retrieving whole data set

Your code for count is making request and retrieving data for whole table, that will crash on larger tables when it will try to retrieve more than 100k records, you have identical query and count methods:

public function query($query)
{
    $sql = $this->pdo->prepare($query);
    $rows=$sql->execute($this->escape);

    return $sql->fetchAll(PDO::FETCH_ASSOC);
}

public function count($query)
{
    $sql = $this->pdo->prepare($query);
    $rows=$sql->execute($this->escape);

    return $sql->rowCount();
}

All other databables implementation modify query so query itself will count records like select count(*) from table/

any idea get data from store procedure?

i created a store procedure, and i want call it.
but i think it's not possible use $datatables->query("CALL store_procedure()") ,
cz query's function will create new statement select like select * from (CALL store_procedure()) and i thinks it doesn't work.
I try to find how to execute store procedure, but until now i have no idea.

Can you help me?
Thanks

Having trouble to return ajax data

Can't generate the json.
ajax code:

$config = [ 'host'     => 'localhost',
'port'     => '3306',
 'username' => 'root',
'password' => '',
'database' => 'sys_db_gestao' ];
$dt = new Datatables( new MySQL($config) );
$dt->query("SELECT t.id as tokenId, t.tokenCode as tokenCode, cli.name as clientName,
cit.name as cityName,
 cast(DATE_FORMAT(t.dateOpen,'%d/%m/%Y %H:%i:%s') as char(20)) as dateOpen,
t.status as tokenstatus
FROM token t
LEFT JOIN client cli on cli.id = t.idClient
LEFT JOIN city cit on cit.id = t.idCity
");
echo $dt->generate();

and the browser console gives me this:

A PHP Error was encountered

Severity: 4096

Message: Argument 1 passed to PHPSQLParser\builders\WhereBuilder::build() must be of the type array, boolean given, called in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\gestao\vendor\greenlion\php-sql-parser\src\PHPSQLParser\builders\SelectStatementBuilder.php on line 74 and defined

Filename: builders/WhereBuilder.php

Line Number: 112

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: builders/WhereBuilder.php

Line Number: 114

A PHP Error was encountered

Severity: 4096

Message: Argument 1 passed to PHPSQLParser\builders\WhereBuilder::build() must be of the type array, boolean given, called in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\gestao\vendor\greenlion\php-sql-parser\src\PHPSQLParser\builders\SelectStatementBuilder.php on line 74 and defined

Filename: builders/WhereBuilder.php

Line Number: 112

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: builders/WhereBuilder.php

Line Number: 114


Fatal error: Call to a member function fetch_assoc() on a non-object in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\gestao\vendor\ozdemir\datatables\src\DB\MySQL.php on line 40

Help me?

DataTables Editor ile uyumluluk

selamlar. gayet kullanışlı bir paket. teşekkür ederim öncelikle.

bir süredir kullanıyorum ancak şimdi DataTables Editor eklentisini edindim. veri güncelleme işlemleri ile yani editor ile uyumlu çalışır mı yoksa Editor eklentisinin server-side paketiyle mi devam etmeliyim?

teşekkürler.

reload trigger alert error

I trying to edit a row through custom modal and send it to the backend.
after row has being edit I trigger the ajax.reload/draw method so the table refreshes

window.DatatableInstanceClosure.ajax.reload();
window.DatatableInstanceClosure.draw();

no matter which I use I still get alert error through after clicking ok the content does refreshes and data is correct
but the alert does that on every update.

image

the really strange thing here that the alert doesn't show up when I trigger the reload method when I add a new data to the table, only on data the has being edit.

edit: even if I don't really change the data at all and trigger the server to reload it still alert the same error.
one of the most confusing bugs I ever saw with this lib

Error on your description

should be PORT and not post. thanks!

$config = [ 'host' => 'localhost',
'post' => '3306',
'username' => 'homestead',
'password' => 'secret',
'database' => 'sakila' ];

How to get working without composer

hi, i dont want to go down the route of using Composer and ive tried downloading the source and re-creating the folders and then tried the basic.php script..... however i keep getting:

Fatal error: Uncaught Error: Class 'Ozdemir\Datatables\Datatables' not found in C:\wamp64\www\basic.php on line 15
Error: Class 'Ozdemir\Datatables\Datatables' not found in C:\wamp64\www\basic.php on line 15

So what could i be doing wrong? Thanks

why not data

hello,you have done a good work,but when do your example,my get following:

{"draw":false,"recordsTotal":"269","recordsFiltered":"269","data":[]}

not data showing?

A small wish

Can you change all private functions to protected. A have written "class MySqlDatatables extends Datatables" that optimizes count of result rows. In this class I override methods query and execute.

class MySqlDatatables extends Datatables {

public function query($query)
{
    $this->columns = $this->setcolumns($query);
    $columns = implode(", ", $this->columns);
    $query = rtrim($query, "; ");
    $this->sql = "Select SQL_CALC_FOUND_ROWS $columns from ($query)t";

    return $this;
}

protected function execute()
{
    $this->recordstotal = $this->db->count($this->sql); // unfiltered data count is here.
    $where = $this->filter();

    $this->data = $this->db->query($this->sql . $where . $this->orderby() . $this->limit());
    $rowCounts = $this->db->query("SELECT FOUND_ROWS() as rowCount");  // filtered data count is here.
    $this->recordsfiltered = $rowCounts[0]['rowCount'];

    $this->query = $this->sql . $where . $this->orderby() . $this->limit();

    return $this;
}

}

in laravel it doesn't work

Return this

{
  "draw": 0,
  "recordsTotal": 4,
  "recordsFiltered": 4,
  "data": [
    [
      "3",
      "test"
    ],
    [
      "4",
      "test2"
    ],
  ]
}

Should be:

{
  "draw": 0,
  "recordsTotal": 4,
  "recordsFiltered": 4,
  "data": [
    {
      "id":"3",
      "name":"test"
    },
    {
      "id": "4",
      "name":"test2"
    }
  ]
}

This is the request

{
	"draw": 1,
	"columns": [{
		"data": "contractor_name",
		"name": "",
		"searchable": true,
		"orderable": true,
		"search": {
			"value": "",
			"regex": false
		}
	}, {
		"data": "name",
		"name": "",
		"searchable": true,
		"orderable": true,
		"search": {
			"value": "",
			"regex": false
		}
	}, {
		"data": "cod",
		"name": "",
		"searchable": true,
		"orderable": true,
		"search": {
			"value": "",
			"regex": false
		}
	}, {
		"data": "contract_cod",
		"name": "",
		"searchable": true,
		"orderable": true,
		"search": {
			"value": "",
			"regex": false
		}
	}, {
		"data": "supervisor_name",
		"name": "",
		"searchable": true,
		"orderable": true,
		"search": {
			"value": "",
			"regex": false
		}
	}, {
		"data": "status",
		"name": "",
		"searchable": true,
		"orderable": true,
		"search": {
			"value": "",
			"regex": false
		}
	}],
	"order": [{
		"column": 0,
		"dir": "asc"
	}],
	"start": 0,
	"length": 1,
	"search": {
		"value": "",
		"regex": false
	}
}

In codeigniter if it works

How to unset a field?

Hi,

Thank you for your excellent job.

I want to unset a field that I have selected in my query statement. For example:

$dt->query("SELECT id, name, phone");

I only want to get name and phone in my table but, I also need id field to use it in my edit function but I do not need id in my table output.

$dt->edit('name', function($data) {
return callback_view($data['id'], $data['name']);
});

Thank you.

Array access with invalid values return E_NOTICE since PHP 7.4 and may break queries

I'm getting this with E_NOTICE enabled which breaks the query since PHP 7.4:

Notice: Trying to access array offset on value of type null in vendor/ozdemir/datatables/src/QueryBuilder.php on line 214

And this one twice for each column:

Notice: Trying to access array offset on value of type null in vendor/ozdemir/datatables/src/Column.php on line 101

Details on this tweet.

PSAdapter escape is missing single quote

Using the PSAdapter with Prestashop 1.7 the search query is broken since no single quotes are added to the where conditions.
A quick workaround is to modify the escape method:

/**
* @param $string
* @param Query $query
* @return string
*/
public function escape($string, Query $query)
{
     return "'" . pSQL($string) . "'";
 }

Parameter must be an array or an object that implements Countable in

Apache Server,
PHP v7.2.0,
MySQL v5.7.19,

PHP Native


Warning: count(): Parameter must be an array or an object that implements Countable in ***:\***\***\***\vendor\ozdemir\datatables\src\Datatables.php on line 234

Warning: count(): Parameter must be an array or an object that implements Countable in ***:\***\***\***\vendor\ozdemir\datatables\src\Datatables.php on line 243

Slow page load times with large database, 300,000+ rows

Let me start of by saying thanks for sharing this project.

Please forgive me as I am new to working with PHP/Sqlite.

I am getting slow page load times when using the sqlite implementation out of the box.
Load times average 2+ seconds.

Using a similar setup with server side and mysql as provided by datatables I get 150ms load times.

Could you provide suggestions on how to speed up load times?

Error CodeigniterAdapter on tag 2.0.0

I use php 5.6 for my old project, and composer choose package v2.0.0.

I get the error on CodeigniterAdapter.

$query = "Select count(*) as rowcount from ($query)t";
$data = $this->CI->db->query($query, $query->escapes)->result_array();

I know its fixed on v2.0.1. But it require php 7.*.

I want to fix that. But i dont know how to commit to the older tag.

fatal error: Uncaught TypeError

I installed by using composer, my .json looks like this:

"require": {
    "ozdemir/datatables": "2.*",
    "symfony/http-foundation": "^4.2"
},

My "/api/index.php" which should serve the data looks like this:

<?php
require_once '../../vendor/autoload.php';

use Ozdemir\Datatables\Datatables;
use Ozdemir\Datatables\DB\MySQL;

$config = [ 'host'     => 'localhost',
            'port'     => '3306',
            'username' => 'db_user',
            'password' => 'db_pass',
            'database' => 'database' ];

$dt = new Datatables( new MySQL($config) );
$dt->query('SELECT id, domain, ip from domains LIMIT 20');
echo $dt->generate();
?>

When I access this directly it looks like its working, however when accessed from webpage this is the URL being created:

/api/index.php?draw=1&columns%5B0%5D%5Bdata%5D=0&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=1&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=2&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=3&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1544930408846

This gives me theese cryptic messages in return

( ! ) Fatal error: Uncaught TypeError: Return value of 
Ozdemir\Datatables\Iterators\ColumnCollection::get() must be an instance of 
Ozdemir\Datatables\Column, none returned in 
D:\dev\vendor\ozdemir\datatables\src\Iterators\ColumnCollection.php on line 73
--
1 | 0.2043 | 416568 | {main}( ) | ...\index.php:0
2 | 0.2135 | 1146768 | Ozdemir\Datatables\Datatables->generate( ) | ...\index.php:16
3 | 0.2135 | 1146768 | Ozdemir\Datatables\QueryBuilder->setColumnAttributes( ) | ...\Datatables.php:176
4 | 0.2136 | 1147648 | Ozdemir\Datatables\Iterators\ColumnCollection->get( ) | ...\QueryBuilder.php:96

What am I doing wrong here, I have used this HTML:

<table border="0" class="display" id="example" width="100%">
    <thead>
    <tr>
        <th>ID</th>
        <th>Track Name</th>
        <th>Album</th>
        <th>MediaType</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>loading...</td>
    </tr>
    <tfoot>
    <tr>
        <th>ID</th>
        <th>Track Name</th>
        <th>Album</th>
        <th>MediaType</th>
    </tr>
    </tfoot>
    </tbody>
</table>

And this javascript:

<script>

    $(document).ready(function() {

        // Setup - add a text input to each footer cell
        $('#example tfoot th').each( function () {
            var title = $(this).text();
                $(this).html( '<input type="text" class="input is-small" placeholder="Search '+title+'" />' );
        } );

        // DataTable
        var table = $('#example').DataTable( {
            "serverSide": true,
            "responsive": true,
            "ajax": "/api/index.php"
        } );

        // Apply the search
        table.columns().every(function () {
            // Apply the filter
            $("#example tfoot input").on( 'keyup change', function () {
                table
                    .column( $(this).parent().index()+':visible' )
                    .search( this.value )
                    .draw();
            } );
        });

    } );

</script>

Error in line datatables.php 408

Warning: Invalid argument supplied for foreach() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\pos\plugins\Ignited_Datatables.php on line 408

I still get this error even after downloading latest library. Commenting out lines 408 and 409 solves the issue

*turns out I downloaded the wrong version

PostgreSQL driver

Hi... I think your package is amazing while is lightweight and works fine with almost of needs. I have Datatables Editor, but to small works, your package looks nice. But, sadly in my job we use PostgreSQL and so I wasn't able to use the package (also we use php 5.5 =P). With some small changes on a duplicate MySQL adapter, I was able to use the package without any issue (not a lot of tests). So I would like to share with you.


// File: DB\PGSQL.php
<?php namespace Ozdemir\Datatables\DB;

use PDO;
use PDOException;

class PGSQL implements DatabaseInterface
{

    protected $pdo;
    protected $config;
    protected $escape = [];

    public function __construct($config)
    {
        $this->config = $config;
    }

    public function connect()
    {
        $host = $this->config['host'];
        $port = $this->config['port'];
        $user = $this->config['username'];
        $pass = $this->config['password'];
        $database = $this->config['database'];

        try {

            // Changed the dsn
            $this->pdo = new PDO("pgsql:host=$host;dbname=$database;port=$port", "$user", "$pass");
        } catch (PDOException $e) {
            print $e->getMessage();
        }
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        return $this;
    }

    public function query($query)
    {

        
        $sql = $this->pdo->prepare($query);
        $rows=$sql->execute($this->escape);

        return $sql->fetchAll(PDO::FETCH_ASSOC);
    }

    public function count($query)
    {
        $sql = $this->pdo->prepare($query);

        $rows=$sql->execute($this->escape);

        return $sql->rowCount();
    }

    public function escape($string)
    {
        $this->escape[':escape' . (count($this->escape) + 1) ] = '%' . $string . '%';

        return ":escape" . (count($this->escape));
    }
}

Finnaly, is important to change the type casting of the columns (are slightly different in PGSQL). I did that at

// File Datatables.php
protected function filterglobal()
    {
        $searchinput = $this->input('search')['value'];
        $allcolumns = $this->input('columns');

        if ($searchinput == '') {
            return null;
        }

        $search = array();
        $searchinput = preg_replace("/[^\wá-žÁ-Ž]+/", " ", $searchinput);
        foreach (explode(' ', $searchinput) as $word) {
            $lookfor = array();
            foreach ($this->columns as $key => $column) {
                if (array_key_exists($key, $allcolumns)) {
                    if ($allcolumns[ $key ]['searchable'] == 'true') {

                        // This is the magic. Force column type to varchar
                        // I haven't used any if, but in order to use with any db, you probably will handle that  
                        $lookfor[] = $column.'::varchar' . " LIKE " . $this->db->escape($word) . "";
                    }
                }
            }
            $search[] = "(" . implode(" OR ", $lookfor) . ")";
        }

        return implode(" AND ", $search);
    }

Limit and Offset not working with Phalcon\Db\Dialect\Sqlsrv

change code public function makeLimitString(int $take, int $skip) in DBAdapter.php
with
public function makeLimitString(int $take, int $skip)
{
// return " LIMIT $take OFFSET $skip";
return " OFFSET $skip ROWS FETCH NEXT $take ROWS ONLY";
}

Problem with "order by"

ORDERING is not performed due to query sequence. Please help improve this article or section by expanding it
regard mostafa

how to use same reference field name in two different column?

Thanks for your library, it's helped me so much..
I want to ask about use same field name in edit method for different column.
cz i want to make two column contain checkboxes, (eg: column A contain checkbox A, column B contain checkbox B), and use same field for value.
For 1 column in the table, it's possible to use $dt->edit(field_name, function), but how about two different column with same reference field name?
Can we use it?
Thanks.. (sorry for my bad english)

Conditional where clauses?

I'm in the process of upgrading from your 0.9 standalone version that used Active Record. Something that has changed is I've noticed that it appears you can no longer do something like this:

if(isset($_GET['type'])) { $type = explode(',', $_GET['type']); for ($j=0; $j < count($type); $j++) { $datatables->where('ubbt_TR_TYPES.TYPE_ID !=', $type[$j]); } }

Is this still possible and if not do you have recommendations on how to accomplish the above?

NA

This should be deleted, I misunderstood the API.

Forking to update and expand

I am forking this repo to fit my needs and ensuring that it is abstract enough to benefit others. This is going to be an ongoing effort so I'd like to coordinate with the maintainers (looks to be mainly @n1crack) to ensure that the changes are agreed upon and in the interest of the larger community.

I am going to continue to support PHP 5+ for the time being, but I would not be opposed to moving to 7+ in the future, primarily for more strict type adherence. Let me know if there are any concerns from your end.

Here is the fork for the time being: https://github.com/HeathNaylor/datatables

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.