CRUD ASÍNCRONO PHP-MYSQL-JQUERY
Hola, hoy voy a explicar como crear un CRUD asíncrono con el servidor usando PHP-MYSQL-JQUERY, datatables-Jquery y programación orientada a objetos, también utilizaremos Bootstrap y Toast para estilizar un poco el aspecto de la página. Suena muy complicado pero es relativamente sencillo, así que empecemos.
Primero,crearemos nuestra base de datos sencilla para este ejemplo:
create database php_crud;
y ahora crearemos una tabla con algunos registros:
CREATE TABLE `crud` (
`Id` int(2) NOT NULL AUTO_INCREMENT,
`nombre` varchar(25) DEFAULT NULL,
`apellido` varchar(25) DEFAULT NULL,
`direccion` varchar(35) DEFAULT NULL,
`referencias` varchar(45) DEFAULT NULL,
`cuidad` varchar(15) DEFAULT NULL,
`edad` int(2) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
INSERT INTO `crud` VALUES (1,'Alejandro','Castillo','Av Quito','Cerca de la iglesia','Machala',20);
INSERT INTO `crud` VALUES (2,'Liss','Pardo','Av. las Americas','En la esquina','Pasaje',23);
INSERT INTO `crud` VALUES (3,'Antonella','Arias','Av Jose Olmedo','Cerca de una tienda','Machala',19);
INSERT INTO `crud` VALUES (4,'Alejandro','Martinez','Av. Idependencia','Cerca del hospital','Arenillas',23);
UNLOCK TABLES;
DIRECTORIO DE ARCHIVOS
Crearemos esta estructura de archivos en una carpeta dentro de nuestro localhost.
Dentro de la capa presentación vamos a poner todo el contenido que tenga que ver con el aspecto de la página(css, js, bootstrap, toast, etc). Ahí crearemos nuestro index.php que será así:
index.php
This file contains 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
<!DOCTYPE html> | |
<html lang="es"> | |
<head> | |
<meta charset="utf-8"> | |
<title>CRUD | PHP</title> | |
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> | |
<!-- CSS BOOTSTRAP--> | |
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> | |
<link rel="stylesheet" type="text/css" href="css/bootstrap-grid.min.css"> | |
<!-- TOAST --> | |
<link href="toastr-master/build/toastr.css" rel="stylesheet" type="text/css" /> | |
<!-- DATATABLES --> | |
<link rel="stylesheet" type="text/css" href="scripts/datatables/jquery.dataTables.min.css"> | |
<link href="scripts/datatables/buttons.dataTables.min.css" rel="stylesheet"/> | |
<link href="scripts/datatables/responsive.dataTables.min.css" rel="stylesheet"/> | |
</head> | |
<body> | |
<div class="container"> | |
<!-- FORMULARIO --> | |
<h2>SIMPLE CRUD PHP</h2> | |
<div class="row"> | |
<div class="form-row"> | |
<div class="form-group col-md-3"> | |
<input type="text" id="txtID" style="display: none;"> | |
<label for="inputEmail4">Nombre</label> | |
<input type="text" class="form-control" id="txtNombre"> | |
</div> | |
<div class="form-group col-md-3"> | |
<label for="inputPassword4">Apellido</label> | |
<input type="text" class="form-control" id="txtApellido"> | |
</div> | |
<div class="form-group col-md-4"> | |
<label for="inputAddress">Dirección</label> | |
<input type="text" class="form-control" id="txtDireccion" placeholder="Av. Juan Montalvo..."> | |
</div> | |
<div class="form-group col-md-4"> | |
<label for="inputAddress2">Referencias Geograficas</label> | |
<input type="text" class="form-control" id="txtReferencia" placeholder="Hay una arbol cerca..."> | |
</div> | |
</div> | |
<div class="form-row"> | |
<div class="form-group col-md-6"> | |
<label for="inputCity">Ciudad</label> | |
<input type="text" class="form-control" id="txtCuidad"> | |
</div> | |
<div class="form-group col-md-2"> | |
<label for="inputZip">Edad</label> | |
<input type="text" class="form-control" id="txtEdad"> | |
</div> | |
</div> | |
</div> | |
<div class="form-row"> | |
<div class="form-group col-md-12"> | |
<button type="button" class="btn btn-primary" id="btnGuardar">GUARDAR</button> | |
<button type="button" class="btn btn-primary" id="btnActualizar">ACTUALIZAR</button> | |
<button type="button" class="btn btn-primary" id="btnEliminar">ELIMINAR</button> | |
<button type="button" class="btn btn-primary" id="btnDeshacer">DESHACER</button> | |
</div> | |
</div> | |
</div> | |
<!-- TABLA DE DATOS --> | |
<table id="tblDatos"> | |
<thead> | |
<tr> | |
<td>ID</td> | |
<td>Nombre</td> | |
<td>Apellido</td> | |
<td>Dirección</td> | |
<td>Referencias Geograficas</td> | |
<td>Cuidad</td> | |
<td>Edad</td> | |
<td>Opciones</td> | |
</tr> | |
</thead> | |
<tbody> | |
</tbody> | |
</table> | |
<!-- REQUIRED JS SCRIPTS --> | |
<script src="scripts/jquery-3.4.1.min.js"></script> | |
<script src="toastr-master/toastr.js"></script> | |
<script src="js/app.js"></script> | |
<!-- DATATABLES --> | |
<script src="scripts/datatables/jquery.dataTables.min.js"></script> | |
<script src="scripts/datatables/dataTables.buttons.min.js"></script> | |
<script src="scripts/datatables/buttons.html5.min.js"></script> | |
<script src="scripts/datatables/buttons.colVis.min.js"></script> | |
<script src="scripts/datatables/jszip.min.js"></script> | |
<script src="scripts/datatables/pdfmake.min.js"></script> | |
<script src="scripts/datatables/vfs_fonts.js"></script> | |
</body> | |
</html> |
Ahora vamos a la capa lógica y crearemos nuestra clase, con sus respectivos atributos y métodos.
clase.php
This file contains 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 | |
require_once '../capa_datos/conexion.php'; | |
class clase_persona{ | |
Public $id; | |
Public $nombre; | |
Public $apellido; | |
Public $direccion; | |
Public $referencia; | |
Public $cuidad; | |
Public $edad; | |
const TABLA ='crud'; | |
/* *****METODOS***** */ | |
// metodo para guardar datos en la tabla crud | |
public function guardar(){ | |
$conexion = new Conexion(); | |
$consulta = $conexion->prepare('INSERT INTO ' . self::TABLA .' (nombre, apellido,direccion,referencias,cuidad,edad) VALUES(:nombre, :apellido,:direccion,:referencia,:cuidad,:edad)'); | |
$consulta->bindParam(':nombre', $this->nombre, PDO::PARAM_STR); | |
$consulta->bindParam(':apellido', $this->apellido, PDO::PARAM_STR); | |
$consulta->bindParam(':direccion', $this->direccion, PDO::PARAM_STR); | |
$consulta->bindParam(':referencia', $this->referencia, PDO::PARAM_STR); | |
$consulta->bindParam(':cuidad', $this->cuidad, PDO::PARAM_STR); | |
$consulta->bindParam(':edad', $this->edad, PDO::PARAM_INT); | |
return $consulta->execute(); | |
} | |
// Método para actualizar la tabla crud | |
public function actualizar(){ | |
$conexion = new Conexion(); | |
$consulta = $conexion->prepare('UPDATE ' . self::TABLA .' SET nombre = :nombre, apellido = :apellido,direccion= :direccion,referencias = :referencia,cuidad = :cuidad,edad = :edad WHERE Id = :id '); | |
$consulta->bindParam(':id', $this->id, PDO::PARAM_INT); | |
$consulta->bindParam(':nombre', $this->nombre, PDO::PARAM_STR); | |
$consulta->bindParam(':apellido', $this->apellido, PDO::PARAM_STR); | |
$consulta->bindParam(':direccion', $this->direccion, PDO::PARAM_STR); | |
$consulta->bindParam(':referencia', $this->referencia, PDO::PARAM_STR); | |
$consulta->bindParam(':cuidad', $this->cuidad, PDO::PARAM_STR); | |
$consulta->bindParam(':edad', $this->edad, PDO::PARAM_INT); | |
return $consulta->execute(); | |
} | |
// Método para eliminar los datos | |
public function eliminar(){ | |
$conexion = new Conexion(); | |
$consulta = $conexion->prepare('DELETE FROM '. self::TABLA . ' where Id = :id'); | |
$consulta->bindParam(':id', $this->id, PDO::PARAM_INT); | |
return $consulta->execute(); | |
} | |
// Extraer Datos de Base de datos | |
public function tabla(){ | |
$query = "SELECT * from crud"; | |
$conexion = new Conexion(); | |
$consulta = $conexion->prepare($query); | |
$consulta->execute(); | |
$registros = $consulta->fetchAll(); | |
return $registros; | |
} | |
} | |
?> |
Ahora vamos a la capa datos y crearemos la conexión con nuestra base de datos:
conexion.php
This file contains 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 | |
class Conexion extends PDO { | |
private $tipo_de_base = 'mysql'; | |
private $host = 'localhost'; | |
private $nombre_de_base = 'php_crud'; | |
private $usuario = 'root'; | |
private $contrasena = '1234'; | |
public function __construct() { | |
//Sobreescribo el método constructor de la clase PDO. | |
try{ | |
parent::__construct("{$this->tipo_de_base}:dbname={$this->nombre_de_base};host={$this->host};", $this->usuario, $this->contrasena); | |
}catch(PDOException $e){ | |
echo 'Ha surgido un error y no se puede conectar a la base de datos. Detalle: ' . $e->getMessage(); | |
exit; | |
} | |
} | |
} | |
?> |
Ahora vamos a la carpeta ajax y crearemos un switch que nos servirá más tarde.
app.php
This file contains 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 | |
require_once "../capa_logica/clase.php"; | |
$objPersona = new clase_persona(); | |
switch ($_GET["op"]){ | |
case 'datos_tabla': | |
$respuesta=$objPersona->tabla(); | |
//var_dump($respuesta); | |
$c=0; | |
$data= Array(); | |
foreach($respuesta as $row => $item) | |
{ | |
$c++; | |
$data[]=array( | |
"0"=>"<label id='lblid$c'>" . $item["Id"] . "</label>", | |
"1"=>"<label id='lblnombre$c'>" . $item["nombre"] . "</label>", | |
"2"=>"<label id='lblapellido$c'>" . $item["apellido"] . "</label>", | |
"3"=>"<label id='lbldireccion$c'>". $item["direccion"]."</label>", | |
"4"=>"<label id='lblreferencias$c'>" . $item["referencias"] . "</label>", | |
"5"=>"<label id='lblcuidad$c'>" . $item["cuidad"] . "</label>", | |
"6"=>"<label id='lbledad$c'>" . $item["edad"] . "</label>", | |
"7"=>"<button class='btn btn-primary' onclick='agregar(" . $c . ")'>Editar<i class='fa fa-edit'></i></button> " | |
); | |
} | |
$results = array( | |
"sEcho"=>1, //Información para el datatables | |
"iTotalRecords"=>count($data), //enviamos el total registros al datatable | |
"iTotalDisplayRecords"=>count($data), //enviamos el total registros a visualizar | |
"aaData"=>$data); | |
echo json_encode($results); | |
break; | |
case 'guardar': | |
$nombre = $_POST['txtNombre']; | |
$apellido = $_POST['txtApellido']; | |
$direccion = $_POST['txtDireccion']; | |
$referencia = $_POST['txtReferencia']; | |
$cuidad = $_POST['txtCuidad']; | |
$edad = $_POST['txtEdad']; | |
$objPersona->nombre = $nombre; | |
$objPersona->apellido = $apellido; | |
$objPersona->direccion = $direccion; | |
$objPersona->referencia = $referencia; | |
$objPersona->cuidad = $cuidad; | |
$objPersona->edad = $edad; | |
echo $objPersona->guardar(); | |
break; | |
case 'actualizar': | |
$id = $_POST['txtID']; | |
$nombre = $_POST['txtNombre']; | |
$apellido = $_POST['txtApellido']; | |
$direccion = $_POST['txtDireccion']; | |
$referencia = $_POST['txtReferencia']; | |
$cuidad = $_POST['txtCuidad']; | |
$edad = $_POST['txtEdad']; | |
$objPersona->id = $id; | |
$objPersona->nombre = $nombre; | |
$objPersona->apellido = $apellido; | |
$objPersona->direccion = $direccion; | |
$objPersona->referencia = $referencia; | |
$objPersona->cuidad = $cuidad; | |
$objPersona->edad = $edad; | |
echo $objPersona->actualizar(); | |
break; | |
case 'eliminar': | |
$id = $_POST['txtID']; | |
$objPersona->id = $id; | |
echo $objPersona->eliminar(); | |
break; | |
} //Cerrar el switch | |
?> |
Listo, ya tenemos la estructura de nuestro pequeño CRUD, ahora vamos a la capa de presentación y dentro de la carpeta JS crearemos un archivo javascript que controlara nuestro CRUD.
app.js
This file contains 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
$(document).ready(function(){//INICIA FORMULARIO COMPLETO | |
console.log('Formulario Iniciado'); //simple mensaje en al consola del navegador | |
listarDatos(); // LLAMAR A LAFUNCION PARA QUE MESTRE LOS DATOS DE LA BD en la TABLA | |
// EJECUTAR ACCION DE LOS BOTONES | |
$('#btnGuardar').click(function(event){ | |
guardar(); | |
}); | |
$('#btnActualizar').click(function(event){ | |
actualizar(); | |
}); | |
$('#btnEliminar').click(function(event){ | |
eliminar(); | |
}); | |
$('#btnDesahacer').click(function(event){ | |
limpiar(); | |
}); | |
// TERMINA EL FORMULARIO | |
}); | |
// Función para limpiar INPUTS | |
function limpiar(){ | |
$('#txtNombre').val(''); | |
$('#txtApellido').val(''); | |
$('#txtDireccion').val(''); | |
$('txtReferencia').val(''); | |
$('#txtCuidad').val(''); | |
$('#txtEdad').val(''); | |
} | |
// funcion para guardar datos en la BD | |
function guardar(){ | |
var nombre = $('#txtNombre').val(); | |
var apellido = $('#txtApellido').val(); | |
var direccion = $('#txtDireccion').val(); | |
var referencia = $('#txtReferencia').val(); | |
var cuidad = $('#txtCuidad').val(); | |
var edad = $('#txtEdad').val(); | |
var data= 'txtNombre='+nombre+'&txtApellido='+apellido+'&txtDireccion='+ direccion + '&txtReferencia='+ referencia + '&txtCuidad='+ cuidad + '&txtEdad='+ edad; | |
$.ajax({ | |
type:'post', | |
url: '../ajax/app.php?op=guardar', | |
data: data, | |
success:function(resp){ | |
// alert(resp); | |
if(resp==1) | |
{ | |
toastr.success('Registro Almacenado correctamente', 'INFORMACIÓN DEL SISTEMA'); | |
listarDatos(); | |
limpiar(); | |
} | |
else | |
{ | |
toastr.error('Registro no se pudo almacenar', 'INFORMACIÓN DEL SISTEMA'); | |
} | |
} | |
}); | |
} | |
// funcion para actualizar los datos | |
function actualizar(){ | |
var id = $('#txtID').val(); | |
var nombre = $('#txtNombre').val(); | |
var apellido = $('#txtApellido').val(); | |
var direccion = $('#txtDireccion').val(); | |
var referencia = $('#txtReferencia').val(); | |
var cuidad = $('#txtCuidad').val(); | |
var edad = $('#txtEdad').val(); | |
var data= 'txtID='+ id +'&txtNombre='+nombre+'&txtApellido='+apellido+'&txtDireccion='+ direccion + '&txtReferencia='+ referencia + '&txtCuidad='+ cuidad + '&txtEdad='+ edad; | |
$.ajax({ | |
type:'post', | |
url: '../ajax/app.php?op=actualizar', | |
data: data, | |
success:function(resp){ | |
// alert(resp); | |
if(resp==1) | |
{ | |
toastr.success('Registro Actualizado correctamente', 'INFORMACIÓN DEL SISTEMA'); | |
listarDatos(); | |
limpiar(); | |
} | |
else | |
{ | |
toastr.error('Registro no se pudo Actualizar', 'INFORMACIÓN DEL SISTEMA'); | |
} | |
} | |
}); | |
} | |
// funcion para eliminar datos | |
function eliminar(){ | |
var id = $('#txtID').val(); | |
var data = 'txtID='+ id; | |
$.ajax({ | |
type:'post', | |
url: '../ajax/app.php?op=eliminar', | |
data: data, | |
success:function(resp){ | |
// alert(resp); | |
if(resp==1) | |
{ | |
toastr.success('Registro Eliminado correctamente', 'INFORMACIÓN DEL SISTEMA'); | |
listarDatos(); | |
limpiar(); | |
} | |
else | |
{ | |
toastr.error('Registro no se pudo Eliminar', 'INFORMACIÓN DEL SISTEMA'); | |
} | |
} | |
}); | |
} | |
// SUBIR LOS DATOS DE LA TABLA A LOS INPUTS | |
function agregar(fila) | |
{ | |
$("#txtID").val($('#lblid' + fila).html()); | |
$("#txtNombre").val($('#lblnombre' + fila).html()); | |
$("#txtApellido").val($('#lblapellido' + fila).html()); | |
$("#txtDireccion").val($('#lbldireccion' + fila).html()); | |
$("#txtReferencia").val($('#lblreferencias' + fila).html()); | |
$("#txtCuidad").val($('#lblcuidad' + fila).html()); | |
$("#txtEdad").val($('#lbledad'+fila).html()); | |
} | |
// LLENAR TABLA DATOS | |
function listarDatos() | |
{ | |
tabla=$('#tblDatos').dataTable( | |
{ | |
"aProcessing": true,//Activamos el procesamiento del datatables | |
"aServerSide": true,//Paginación y filtrado realizados por el servidor | |
dom: 'Bfrtip',//Definimos los elementos del control de tabla | |
buttons: [ | |
], | |
"ajax": | |
{ | |
url: '../ajax/app.php?op=datos_tabla', | |
type : "get", | |
dataType : "json", | |
error: function(e){ | |
console.log(e.responseText); | |
alert(e); | |
} | |
}, | |
//"lengtMenu": [[5, 10, 50, 25, 50, -1], [5, 10, 50, 25, 50, "Todos"]], | |
"columns" : [ | |
{"data":0, 'orderable': true, 'searchable': true}, | |
{"data":1, 'orderable': true, 'searchable': true}, | |
{"data":2, 'orderable': true, 'searchable': true}, | |
{"data":3, 'orderable': true, 'searchable': true}, | |
{"data":4, 'orderable': true, 'searchable': true}, | |
{"data":5, 'orderable': true, 'searchable': true}, | |
{"data":6, 'orderable': false, 'searchable': false}, | |
{"data":7, 'orderable': false, 'searchable': false}, | |
], | |
"bDestroy": true, | |
"iDisplayLength": 10,//Paginación | |
"order": [[ 0, "asc" ]]//Ordenar (columna,orden) | |
}).DataTable(); | |
} |
Y listo ya tendremos nuestro pequeño CRUD asíncrono usando programación orientada a objetos, viste que fácil que es.
Acá te dejo el link del repositorio por si deseas descargarlo.
Comentarios
Publicar un comentario