Vuoi integrare DataTable nella tua applicazione? DataTable aggiunge controlli di interazione avanzati alle tue tabelle HTML. Inoltre è open-source, quindi tutti possono usarlo gratuitamente. È utile quando la tua tabella ha centinaia di voci. Usando DataTable, otterrai le loro funzionalità integrate come l’ordinamento, la ricerca, l’impaginazione, ecc. In questo articolo, ti mostro come utilizzare DataTable in PHP.
DataTables è una scelta comune per elencare i record tabulari nell’applicazione. Grazie alla sua semplicità e facilità di installazione, gli sviluppatori hanno preferito utilizzarlo.
Per il nostro tutorial, creerò una tabella nel database e visualizzerò i suoi record nel DataTable. L’output finale sarà simile allo screenshot seguente:
Iniziare
Per iniziare, vai al tuo phpMyAdmin e crea la tabella utilizzando la seguente query:
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
La tabella "utenti" ha le colonne nome, cognome ed età. Aggiungi voci fittizie in questa tabella. L’utente può utilizzare la libreria Faker per seminare la tua tabella con voci fittizie. Utilizzando la libreria dei falsi è possibile aggiungere migliaia di voci false nel database in pochi istanti.
Quindi, crea un config.php
file e scrivi un codice per la connessione al database.
config.php
<?php
$conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($conn->connect_errno) {
echo "Error: ". $conn->connect_error;
}
Assicurati di sostituire i segnaposto con i valori effettivi.
Come utilizzare DataTable in PHP
Per integrare DataTable, ciò che farò è recuperare i record dal database, scorrerlo e visualizzarlo in una tabella. E quindi applica DataTable alla tabella HTML.
Crea un index.php
file e aggiungi il codice qui sotto.
<?php
require_once('config.php');
$sql = "SELECT id, first_name, last_name, age FROM users";
$result = $conn->query($sql);
$arr_users = [];
if ($result->num_rows > 0) {
$arr_users = $result->fetch_all(MYSQLI_ASSOC);
}
?>
Nel codice sopra, ho recuperato tutte le righe dalla tabella "utenti" e le ho assegnate alla variabile PHP $arr_users
. Ora, scorrerò questa variabile e creerò la riga della tabella una per una.
<table id="userTable">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</thead>
<tbody>
<?php if(!empty($arr_users)) { ?>
<?php foreach($arr_users as $user) { ?>
<tr>
<td><?php echo $user['first_name']; ?></td>
<td><?php echo $user['last_name']; ?></td>
<td><?php echo $user['age']; ?></td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
Qui, ho dato un id ‘userTable’ alla tabella. La prossima cosa che devo fare è includere i file richiesti di DataTable nell’HTML.
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
Infine, chiama il metodo DataTable() sull’id della tabella dato.
<script>
$(document).ready(function() {
$('#userTable').DataTable();
});
</script>
Il nostro codice finale è il seguente;
<?php
require_once('config.php');
$sql = "SELECT id, first_name, last_name, age FROM users";
$result = $conn->query($sql);
$arr_users = [];
if ($result->num_rows > 0) {
$arr_users = $result->fetch_all(MYSQLI_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Datatable</title>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"/>
</head>
<body>
<table id="userTable">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</thead>
<tbody>
<?php if(!empty($arr_users)) { ?>
<?php foreach($arr_users as $user) { ?>
<tr>
<td><?php echo $user['first_name']; ?></td>
<td><?php echo $user['last_name']; ?></td>
<td><?php echo $user['age']; ?></td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$('#userTable').DataTable();
});
</script>
</body>
</html>
Spero che tu possa imparare a usare DataTable in PHP. Per favore condividi i tuoi pensieri nella sezione commenti qui sotto.
articoli Correlati
- Come convertire HTML in PDF in PHP
- Come esportare i dati del database MySQL in Excel utilizzando PHP
- Come leggere file CSV ed Excel in PHP utilizzando PhpSpreadsheet