Created
July 27, 2024 15:58
-
-
Save Anders87x/5b8fd2521326d484eab25aaa114dbd16 to your computer and use it in GitHub Desktop.
server_processing.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Datos de conexión a la base de datos | |
| $host = 'localhost'; | |
| $db = 'nombre_de_tu_base_de_datos'; | |
| $user = 'tu_usuario'; | |
| $pass = 'tu_contraseña'; | |
| // Conexión a la base de datos | |
| $dsn = "mysql:host=$host;dbname=$db;charset=utf8"; | |
| $pdo = new PDO($dsn, $user, $pass); | |
| // Obtención de los parámetros enviados por DataTables | |
| $limit = $_POST['length']; | |
| $start = $_POST['start']; | |
| $search = $_POST['search']['value']; | |
| // Consulta base | |
| $sql = "SELECT * FROM tu_tabla"; | |
| if (!empty($search)) { | |
| $sql .= " WHERE columna1 LIKE :search OR columna2 LIKE :search"; | |
| } | |
| $sql .= " LIMIT :start, :limit"; | |
| $stmt = $pdo->prepare($sql); | |
| if (!empty($search)) { | |
| $stmt->bindValue(':search', "%$search%", PDO::PARAM_STR); | |
| } | |
| $stmt->bindValue(':start', (int) $start, PDO::PARAM_INT); | |
| $stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT); | |
| $stmt->execute(); | |
| $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); | |
| // Conteo total de registros | |
| $totalSql = "SELECT COUNT(*) FROM tu_tabla"; | |
| $totalStmt = $pdo->prepare($totalSql); | |
| $totalStmt->execute(); | |
| $totalRecords = $totalStmt->fetchColumn(); | |
| // Conteo total de registros filtrados | |
| $filterSql = "SELECT COUNT(*) FROM tu_tabla"; | |
| if (!empty($search)) { | |
| $filterSql .= " WHERE columna1 LIKE :search OR columna2 LIKE :search"; | |
| } | |
| $filterStmt = $pdo->prepare($filterSql); | |
| if (!empty($search)) { | |
| $filterStmt->bindValue(':search', "%$search%", PDO::PARAM_STR); | |
| } | |
| $filterStmt->execute(); | |
| $totalFiltered = $filterStmt->fetchColumn(); | |
| // Preparar los datos para DataTables | |
| $data = array(); | |
| foreach ($rows as $row) { | |
| $data[] = array( | |
| $row['columna1'], | |
| $row['columna2'], | |
| // Agrega más columnas según sea necesario | |
| ); | |
| } | |
| // Formato de respuesta para DataTables | |
| $json_data = array( | |
| "draw" => intval($_POST['draw']), | |
| "recordsTotal" => intval($totalRecords), | |
| "recordsFiltered" => intval($totalFiltered), | |
| "data" => $data | |
| ); | |
| // Enviar respuesta en formato JSON | |
| echo json_encode($json_data); | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment