2014-09-05 37 views
13

Va bene così sto provando a visualizzare le informazioni dal mio database usando jQuery DataTable (DataTables.net). Posso farlo funzionare bene visualizzando l'intera tabella 'note', ma mi piacerebbe solo visualizzare le note che non sono state lette. Quindi ho bisogno di includere una clausola WHERE in qualche modo, ma non sono chiaro sul modo migliore per farlo.Come utilizzare la clausola 'WHERE' utilizzando ssp.class.php DataTables

Ecco come mi momento si possono visualizzare l'intera tabella:

// DB table to use 
$table = 'Notes'; 

// Table's primary key 
$primaryKey = 'CID'; 

// 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' => 'CID', 'dt' => 0), 

array(
    'db'  => 'CID', 
    'dt'  => 0, 
    'formatter' => function($d, $row) { 
     return '<a href="profile.php?search='.$d.'" target="_Blank">'.$d."</a>"; 
    } 
), 

array('db' => 'Title', 'dt' => 1), 
array('db' => 'Name', 'dt' => 2), 
array(
    'db'  => 'Date', 
    'dt'  => 3, 
    'formatter' => function($d, $row) { 
     return date('jS M y', strtotime($d)); 
     } 
    ) 
); 

// SQL server connection information 
$sql_details = array(
'user' => '*DB_USER*', 
'pass' => '*Password*', 
'db' => '*DatabaseName*', 
'host' => 'localhost' 
); 
require('ssp.class.php'); 

echo json_encode(
    SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns) 
); 

avrei bisogno l'equivalente di SELECT * FROM Notes WHERE Status ='Unread'

+0

Hai letto questo link? https://datatables.net/forums/discussion/20953/where-clause-using-ssp-class-php-solved. Speriamo che funzioni. –

risposta

25

è necessario modificare DataTable Funzioni predefinite per fare questa azione!

utilizzare questa classe ssp.class.php personalizzato

Link

come usare?

uso come in questo esempio:

require('ssp.class.php'); 
$where = "Status ='Unread'"; 
echo json_encode(
    SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns,$where) 
); 

se si imposta il parametro $ dove, questa classe aggiungere dove selezionare dichiarazione!

Aggiornamento:

DataTable nel 2015 aggiungono complesso metodo

questo nuovo metodo può impostare clausola where nella query!

+2

C'è un errore nel codice, dovrebbe essere: SSP :: complex ($ _GET, $ sql_details, $ table, $ primaryKey, $ columns, $ where) Il metodo complesso è quello che ha aggiunto il supporto per dove clausola, usando SSP: semplice ignorerà la query che hai appena aggiunto. Ho modificato la tua risposta. Controlla la documentazione: https://github.com/DataTables/DataTablesSrc/blob/master/examples/server_side/scripts/ssp.class.php#L276 –

+0

prima leggi la risposta! Io creo una classe personalizzata e la uso (controlla il link github), come ho detto non c'è un metodo complesso nel 2014, è per questo che ho scritto quella classe! –

+0

Il mio male allora! mi dispiace per il fatto che ho pensato che fosse un errore di battitura, in realtà era piuttosto confuso. Probabilmente sarebbe una buona idea se si aggiungesse il codice complesso sotto il paragrafo di aggiornamento, probabilmente si verrebbe a creare confusione. –

2

È possibile utilizzare la clausola WHERE del genere;

$data = SSP::sql_exec($db, $bindings, 
    "SELECT SQL_CALC_FOUND_ROWS ".implode(", ", SSP::pluck($columns, 'db'))." 
    FROM $table where Status = 'Unread' // <--where clause here 
    $where 
    $order 
    $limit" 
); 
+1

Come usarlo con 'echo json_encode ( SSP :: simple ($ _GET, $ sql_details, $ table, $ primaryKey, $ colonne) )' perché sto ottenendo i dati con json_encode – NewUser

8

Bene .. non è possibile senza modificare o estendere SSP. Questo è lo stile piuttosto male con un sacco di codice copiato, ma SSP non consente una migliore personalizzazione ...

class SSPCustom extends SSP 
{ 
    /** 
    * @param array $request Data sent to server by DataTables 
    * @param array $sql_details SQL connection details - see sql_connect() 
    * @param string $table SQL table to query 
    * @param string $primaryKey Primary key of the table 
    * @param array $columns Column information array 
    * @param string $whereCustom Custom (additional) WHERE clause 
    * @return array   Server-side processing response array 
    */ 
    static function simpleCustom ($request, $sql_details, $table, $primaryKey, $columns, $whereCustom = '') 
    { 
     $bindings = array(); 
     $db = self::sql_connect($sql_details); 

     // Build the SQL query string from the request 
     $limit = self::limit($request, $columns); 
     $order = self::order($request, $columns); 
     $where = self::filter($request, $columns, $bindings); 

     if ($whereCustom) { 
      if ($where) { 
       $where .= ' AND ' . $whereCustom; 
      } else { 
       $where .= 'WHERE ' . $whereCustom; 
      } 
     } 

     // Main query to actually get the data 
     $data = self::sql_exec($db, $bindings, 
      "SELECT SQL_CALC_FOUND_ROWS `".implode("`, `", self::pluck($columns, 'db'))."` 
      FROM `$table` 
      $where 
      $order 
      $limit" 
     ); 

     // Data set length after filtering 
     $resFilterLength = self::sql_exec($db, 
      "SELECT FOUND_ROWS()" 
     ); 
     $recordsFiltered = $resFilterLength[0][0]; 

     // Total data set length 
     $resTotalLength = self::sql_exec($db, 
      "SELECT COUNT(`{$primaryKey}`) 
      FROM `$table` 
      WHERE " . $whereCustom 
     ); 
     $recordsTotal = $resTotalLength[0][0]; 


     /* 
     * Output 
     */ 
     return array(
      "draw"   => intval($request['draw']), 
      "recordsTotal" => intval($recordsTotal), 
      "recordsFiltered" => intval($recordsFiltered), 
      "data"   => self::data_output($columns, $data) 
     ); 
    } 
} 

chiamata con:

echo json_encode(
    SSPCustom::simpleCustom($_GET, $sql_details, $table, $primaryKey, $columns, "Status ='Unread'") 
); 

non testate

+0

Grazie! ha funzionato per me –

0

Sono stato anche in grado di risolvere questo problema ma inserendo del codice nella funzione di filtro ssp.class.php. Di seguito è riportato l'elenco per la funzione con un esempio personalizzato dove clausola inserita. La funzione "semplice" di quella classe funzionerà senza ulteriori truccamenti da parte della giuria. Il vantaggio è che funzionerà correttamente con la funzione di ricerca del testo del datatable.

static function filter ($request, $columns, &$bindings) 
{ 
    $globalSearch = array(); 
    $columnSearch = array(); 
    $dtColumns = self::pluck($columns, 'dt'); 

    if (isset($request['search']) && $request['search']['value'] != '') { 
     $str = $request['search']['value']; 

     for ($i=0, $ien=count($request['columns']) ; $i<$ien ; $i++) { 
      $requestColumn = $request['columns'][$i]; 
      $columnIdx = array_search($requestColumn['data'], $dtColumns); 
      $column = $columns[ $columnIdx ]; 

      if ($requestColumn['searchable'] == 'true') { 
       $binding = self::bind($bindings, '%'.$str.'%', PDO::PARAM_STR); 
       $globalSearch[] = "`".$column['db']."` LIKE ".$binding; 
      } 
     } 
    } 

    // Individual column filtering 
    for ($i=0, $ien=count($request['columns']) ; $i<$ien ; $i++) { 
     $requestColumn = $request['columns'][$i]; 
     $columnIdx = array_search($requestColumn['data'], $dtColumns); 
     $column = $columns[ $columnIdx ]; 

     $str = $requestColumn['search']['value']; 

     if ($requestColumn['searchable'] == 'true' && 
     $str != '') { 
      $binding = self::bind($bindings, '%'.$str.'%', PDO::PARAM_STR); 
      $columnSearch[] = "`".$column['db']."` LIKE ".$binding; 
     } 
    } 

    // Combine the filters into a single string 
    $where = ''; 

    if (count($globalSearch)) { 
     $where = '('.implode(' OR ', $globalSearch).')'; 
    } 

    if (count($columnSearch)) { 
     $where = $where === '' ? 
      implode(' AND ', $columnSearch) : 
      $where .' AND '. implode(' AND ', $columnSearch); 
    } 

     //------------------------------------------------------------ 
     //############################################################ 
     //EXAMPLE ADDITIONAL WHERE CONDITIONS HERE. THIS IS EQUIVALENT 
     //TO "WHERE id = 1" 
     $where = ($where === '') ? 
      "id = ".self::bind($bindings, 1, PDO::PARAM_INT) : 
      $where ." AND "."id = ".self::bind($bindings, 1, PDO::PARAM_INT); 
     //############################################################ 
     //############################################################ 
     //------------------------------------------------------------ 


    if ($where !== '') { 
     $where = 'WHERE '.$where; 
    } 

    return $where; 
}