ServerSide DataTable com PHP e MySQL
Olá prezados,
Alguém poderia me ajudar com server side no datatable com php?
Eu já procurei em vários locais na web, encontrei alguns tutoriais, mais nenhum serviu para a minha aplicação, se alguém quiser dados para acessar o meu sistema para tentar poder me ajudar eu agradeço.
http://admin.efraiminformatica.com.br
usuario: convidado
senha: nameiswhat
No menu filmes em listar, eu tenho uma listagem da tabelas de banco de dados com mais de 3 mil registros, e o mesmo trava quando eu acesso este módulo de listagem, já tentei instalar os códigos que encontrei na internet, mais não consegui funcionar, utilizo uma estrutura de links em query string avançado, preciso fazer esta aplicação funcionar posso colocar aqui também os códigos, segue:
esta é a index.php da pasta filmes da minha view. Notem que pra resolver o problema de travamento eu coloque um limite de 50. Mais está listando apenas 50, quero os mais de 3 mil.
<table id="datatable" class="table table-striped table-bordered bootstrap-datatable datatable">
<thead>
<tr class=\"warning\">
<th>TOMBO</th>
<th>T�TULO ORIGINAL</th>
<th>T�TULO NACIONAL</th>
<th>ANO</th>
<th>DIREçãO</th>
<th>Aç�ES/LISTAGEM</th>
</tr>
</thead>
<tbody>
<?php
$base = BASE;
$empty = filter_input(INPUT_GET, 'empty', FILTER_VALIDATE_BOOLEAN);
if ($empty):
WLMsg("Oppsss: Você tentou editar um módulo que não existe no sistema!", WS_INFOR);
endif;
$action = filter_input(INPUT_GET, 'action', FILTER_DEFAULT);
if ($action):
$filmAction = filter_input(INPUT_GET, 'cod', FILTER_VALIDATE_INT);
$filmSelect = new AdminFilme;
switch ($action):
case 'delete':
$filmSelect->ExeDelete($filmAction);
WLMsg($filmSelect->getError()[0], $filmSelect->getError()[1]);
break;
default :
WLMsg("Ação não foi identificada pelo sistema, favor utilize os botões!", WS_ALERT);
endswitch;
endif;
$empi = 50;
$readAcervo = new Read;
$readAcervo->ExeRead("medien", "order by tombo asc limit 50");
if ($readAcervo->getResult()):
foreach ($readAcervo->getResult() as $listar):
?>
<tr>
<td><?= $listar->tombo; ?></td>
<td><?= $listar->titulooriginal; ?></td>
<td><?= $listar->titulonacional; ?></td>
<td><?= $listar->ano; ?></td>
<td><?= $listar->direcao; ?></td>
<td>
<a href="#" onclick="javascript:window.location.href = '<?= $base; ?>/painel.php?exe=filmes/index&cod=<?= $listar->tombo; ?>';" class="btn btn-small btn-primary" title="Ver <?= $listar->titulonacional; ?>"><i class="halflings-icon white eye-open"></i></a>
<a href="#" onclick="javascript:window.location.href = '<?= $base; ?>/painel.php?exe=filmes/update&codigo=<?= $listar->tombo; ?>';" class="btn btn-info btn-small" title="Editar <?= $listar->titulonacional; ?>"><i class="halflings-icon white edit"></i></a>
<a href="#" onclick="javascript:window.location.href = '<?= $base; ?>/painel.php?exe=filmes/index&cod=<?= $listar->tombo; ?>&action=delete';" class="btn btn-danger btn-small" title="Deletar <?= $listar->titulonacional; ?>"><i class="halflings-icon white trash"></i></a>
</td>
</tr>
<?php
endforeach;
else:
// $Pager->ReturnPage();
WLMsg("Desculpe, ainda não existem empresas cadastradas!", WS_INFOR);
endif;
?>
</tbody>
</table>
Agora vou mostrar os códigos do server_processing.php:
<?php
include_once("../conexao/conecta.php");
/ *
* Easy set variables
*/
/* Array of database columns which should be read and sent back to DataTables. Use a space where
* you want to insert a non-database field (for example a counter or static image)
*/
$aColumns = array('tombo', 'titulooriginal', 'titulonacional', 'ano','direcao');
/ Indexed column (used for fast and accurate table cardinality) /
$sIndexColumn = "id";
/ DB table to use /
$sTable = "medien";
/ Database connection information /
$gaSql['user'] = USER;
$gaSql['password'] = PASS;
$gaSql['db'] = BANCO;
$gaSql['server'] = HOST;
/ *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/
/*
* MySQL connection
*/
$gaSql['link'] = mysql_pconnect($gaSql['server'], $gaSql['user'], $gaSql['password']) or
die('Could not open connection to server');
mysql_select_db($gaSql['db'], $gaSql['link']) or
die('Could not select database ' . $gaSql['db']);
/*
* Paging
*/
$sLimit = "";
if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
$sLimit = "LIMIT " . intval($_GET['iDisplayStart']) . ", " .
intval($_GET['iDisplayLength']);
}
/*
* Ordering
*/
$sOrder = "";
if (isset($_GET['iSortCol_0'])) {
$sOrder = "ORDER BY ";
for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
$sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . " " .
($_GET['sSortDir_' . $i] === 'asc' ? 'asc' : 'desc') . ", ";
}
}
$sOrder = substr_replace($sOrder, "", -2);
if ($sOrder == "ORDER BY") {
$sOrder = "";
}
}
/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
$sWhere = "";
if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {
$sWhere = "WHERE (";
for ($i = 0; $i < count($aColumns); $i++) {
$sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch']) . "%' OR ";
}
$sWhere = substr_replace($sWhere, "", -3);
$sWhere .= ')';
}
/ Individual column filtering /
for ($i = 0; $i < count($aColumns); $i++) {
if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
if ($sWhere == "") {
$sWhere = "WHERE ";
} else {
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
}
}
/*
* SQL queries
* Get data to display
*/
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . "
FROM $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query($sQuery, $gaSql['link']) or die(mysql_error());
/ Data set length after filtering /
$sQuery = "
SELECT FOUND_ROWS()
";
$rResultFilterTotal = mysql_query($sQuery, $gaSql['link']) or die(mysql_error());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];
/ Total data set length /
$sQuery = "
SELECT COUNT(" . $sIndexColumn . ")
FROM $sTable
";
$rResultTotal = mysql_query($sQuery, $gaSql['link']) or die(mysql_error());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];
/*
* Output
*/
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
while ($aRow = mysql_fetch_array($rResult)) {
$row = array();
for ($i = 0; $i < count($aColumns); $i++) {
if ($aColumns[$i] == "version") {
/* Special output formatting for 'version' column */
$row[] = ($aRow[$aColumns[$i]] == "0") ? '-' : $aRow[$aColumns[$i]];
} else if ($aColumns[$i] != ' ') {
/* General output */
$row[] = $aRow[$aColumns[$i]];
}
}
$output['aaData'][] = $row;
}
echo json_encode($output);
Agora vou mostrar os códigos do meu javascript custom.js:
$('#datatable').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span12'i><'span12 center'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page",
"bJQueryUI": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../server_side/server_processing.php"
}
});
Pessoal vou mostrar onde cada arquivo está nas pastas, vou colocar a estrutura:
o arquivo index.php se encontra nesta pasta: public_html/admin/views/filmes/index.php
O arquivo server_processing.php se encontra na pasta: public_html/admin/server_side/server_processing.php
O arquivo custom.js se encontra na pasta: public_html/admin/js/custom.js
O arquivo de conexao se encontra na pasta: public_html/admin/conexao/conecta.php
Utilizo uma programação diferente do que existe no server_processing.php
Utilizo uma estrutura um pouco mais avançada que aprendi em algumas aulas do Robson da Upinside, eu poderia adaptar meus códigos de CRUD no arquivo server_processing.php, mais como eu não entendi ao certo este script serverside, decidir colocar da forma que está.
Então pessoal preciso ver se alguém consegue me ajudar com este sisteminha aí.
Discussão (9)
Carregando comentários...