Как добавить условие Mysql в DataTables?

Есть вот такой замечательный скрипт грида
datatables.net/examples/server_side/simple.html
Как добавить туда условия выбора из базы Mysql?
например
$result = mysql_query("SELECT * FROM `objects` WHERE raiting RLIKE '$str|$str2' ORDER BY `actualtime`  DESC   ");


я так понимаю нужно здесь принимать изменения в server_processing.php
// DB table to use
$table = 'objects';

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

// 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'        => 'actualtime',
        'dt'        => 0,
        'formatter' => function( $d, $row ) {
        	return gmdate("Y-m-d\TH:i:s", $d);
        
        }
    ),

	array( 
	
		'db' => 'id','dt' => 'id' ,
		'db' => 'login_user', 'dt' => 1 ,
		'formatter' => function( $d, $row ) {
      return "<a href=\"objectsinfo.php?id=".$row['name']."\">$d</a>";
    }),
	array( 'db' => 'rayon',  'dt' => 2 ),
	array( 'db' => 'manager',   'dt' => 3 ),
	array( 'db' => 'tip',     'dt' => 4 ),
	array( 'db' => 'actual_time',     'dt' => 5 ),

);

// SQL server connection information
$sql_details = array(
	'user' => '11',
	'pass' => '11',
	'db'   => '11',
	'host' => 'localhost'
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require( 'ssp.class.php' );

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


а это файл вывода objects.php
echo"

<script type='text/javascript' language='javascript' class='init'>
$(document).ready(function() {
    $('#example').dataTable( {
        'processing': true,
        'serverSide': true,
        'ajax': 'system/server_side/examples/server_side/scripts/server_processing.php'

            
    } );
} );

	</script>";

echo'
	<section class="content">
    <div class="row">
  
            <div class="container">      

			<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
				<thead>
					<tr>
						<th></th>
						<th data-class="expand"><center>Адрес</center></th>
						<th>Район</th>
						<th>Менеджер</th>
						<th>Тип</th>
						<th>Время</th>
					
					</tr>
				</thead>

			</table>

			


</div></div></div>
';
  • Вопрос задан
  • 1145 просмотров
Решения вопроса 1
@asdz
Все очень просто. Допустим вы хотите добавить кастомный серверный фильтр, который будет трансформироваться в sql запрос.
Добавляете к инициализатору грида:
"fnServerData": function (sSource, aoData, fnCallback) {
            var sParam = jQuery("#контейнер формы *").serializeArray();
            //console.info(sParam);
            aoData = aoData.concat(sParam);
            jQuery.getJSON(sSource, aoData, function (json) {
                fnCallback(json)
            });
        },

на сервере получаете вместе с данными грида значения элементов внутри контейнера формы. Затем конструируете запрос в серверном скрипте ssp.class.php подпилив функцию simple добавив обработку своих фильтров.
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@kostya572
Максим, есть более простое решение:
заменить в server_processing.php
echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

на
echo json_encode(
    SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns, null, "raiting like '%a%'" )
);
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы