Lo primero que debemos hacer es crear la estructura de nuestro proyecto, luego nuestra base de datos con el nombre, crudfecth y luego nuestra tabla productos, con la siguientes estructura.
CREATE TABLE `productos` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `codigo` varchar(20) COLLATE utf8_spanish_ci NOT NULL, `producto` varchar(255) COLLATE utf8_spanish_ci NOT NULL, `precio` decimal(10,2) NOT NULL, `cantidad` int(11) NOT NULL );
Posteriormente crearemos un archivo con el nombre index.php,
Ejemplo:
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registro de Productos</title> <!--Puedes utilizar el cdn de bootstrap para los estilos--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> </head> <body> <div class="container"> <div class="row"> <form class="col-lg-4" id="form"> <div class="card border-primary"> <div class="card-header bg-primary"> <h5 class="card-title text-center">Registro de Productos</h5> </div> <div class="card-body"> <div class="form-group"> <label for="">Codigo</label> <input type="hidden" class="form-control" name="idp" id="idp" value=""> <input type="text" placeholder="codigo" class="form-control" name="codigo" id="codigo" autocomplete="off" required> </div> <div class="form-group"> <label for="">Producto</label> <input type="text" placeholder="Descripción" class="form-control" name="producto" id="producto" autocomplete="off" required> </div> <div class="form-group"> <label for="">Precio</label> <input type="text" placeholder="Precio" class="form-control" name="precio" id="precio" autocomplete="off" required> </div> <div class="form-group"> <label for="">Cantidad</label> <input type="text" placeholder="Cantidad" class="form-control" name="cantidad" id="cantidad" autocomplete="off" required> </div> <input type="button" class="btn btn-primary btn-block" id="registrar" value="Registrar"> </div> </div> </form> <div class="col-lg-8"> <table class="table table-light table-hover table-responsive"> <thead class="thead-dark"> <tr> <th>ID</th> <th>PRODUCTO</th> <th>PRECIO</th> <th>CANTIDAD</th> <th>ACCIONES</th> </tr> </thead> <tbody id="resultado"> </tbody> </table> </div> </div> </div> <!--Hace referencia a nuestro archivo script--> <script src="js/script.js"></script> <!--Hace referencia al plugin SweetAlert2--> <script src="js/sweetalert2@9.js"></script> <!-- Hace referencia a los icono de font Awesome--> <script src="js/all.min.js"></script> </body> </html>
Ahora crearemos la conexion PDO a nuestra base de datos. en mi caso se llama crudfecth
<?php $servidor = "mysql:dbname=crudfecth;host=localhost"; $usuario = "root"; $password = ""; try { $pdo = new PDO($servidor, $usuario, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); } catch (PDOException $e) { echo "Conexión fallida:" . $e->getMessage(); } ?>
Ahora Crearemos nuestro archivo script.js para Listar, Registrar, Modificar y Eliminar. También para las notificaciones comenzaremos a utilizar el plugin Sweetalert2.
ListarProductos(); function ListarProductos() { fetch("consulta.php", { method: 'POST' }).then(response => response.text()).then(response => { resultado.innerHTML = response; }).catch(error => console.log(error)); } registrar.addEventListener("click", (e) => { e.preventDefault(); fetch("ajax.php", { method: 'POST', body: new FormData(form) }).then(response => response.text()).then(response => { if (response == "ok") { Swal.fire({ icon: 'success', title: 'Registrado', showConfirmButton: false, timer: 1500 }); idp.value = ""; form.reset(); ListarProductos(); } else if (response == "modificado") { Swal.fire({ icon: 'success', title: 'Modificado', showConfirmButton: false, timer: 1500 }); idp.value = ""; form.reset(); ListarProductos(); registrar.value = "Registrar"; } else { Swal.fire({ icon: 'error', title: 'Error al registrar', showConfirmButton: false, timer: 1500 }); } }).catch(error => console.log(error)); }); function eliminar(id) { Swal.fire({ title: 'Esta seguro de eliminar?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Si!', cancelButtonText: 'No' }).then((result) => { if (result.isConfirmed) { fetch("eliminar.php", { method: "POST", body: JSON.stringify({ id: id }) }).then(response => response.text()).then(response => { ListarProductos(); Swal.fire({ icon: 'success', title: 'Eliminado', showConfirmButton: false, timer: 1500 }) }).catch(error => console.log(error)); } }); } function editar(id) { fetch("editar.php", { method: "POST", body: JSON.stringify({ id: id }) }).then(response => response.json()).then(response => { idp.value = response.id; codigo.value = response.codigo; producto.value = response.producto; precio.value = response.precio; cantidad.value = response.cantidad; registrar.value = "Actualizar"; }).catch(error => console.log(error)); }
Posteriormente código del lado del servidor.
- Método listar
<?php require_once "conexion.php"; $consulta = $pdo->prepare("SELECT * FROM productos ORDER BY id DESC"); $consulta->execute(); $result = $consulta->fetchAll(PDO::FETCH_ASSOC); foreach ($result as $data) { echo " <tr> <td>" . $data['id'] . "</td> <td>" . $data['producto'] . "</td> <td>" . $data['precio'] . "</td> <td>" . $data['cantidad'] . "</td> <td> <button type='button' id='editar' class='btn btn-success' onclick=editar('" . $data['id'] . "')><i class='fas fa-edit'></i></button> <button type='button' id='eliminar' class='btn btn-danger'><i class='fas fa-trash-alt' onclick=eliminar('" . $data['id'] . "')></i></button> </td> </tr> "; } ?>
- Método registrar y modificar
<?php if (isset($_POST)) { if ($_POST['idp'] == "") { require "conexion.php"; $codigo = $_POST['codigo']; $producto = $_POST['producto']; $precio = $_POST['precio']; $cantidad = $_POST['cantidad']; $query = $pdo->prepare("INSERT INTO productos (codigo, producto, precio, cantidad) VALUES (:codigo, :producto, :precio, :cantidad)"); $query->bindParam(":codigo", $codigo); $query->bindParam(":producto", $producto); $query->bindParam(":precio", $precio); $query->bindParam(":cantidad", $cantidad); $query->execute(); echo "ok"; $pdo = null; }else{ require "conexion.php"; $codigo = $_POST['codigo']; $producto = $_POST['producto']; $precio = $_POST['precio']; $cantidad = $_POST['cantidad']; $id = $_POST['idp']; $query = $pdo->prepare("UPDATE productos SET codigo=:codigo, producto=:producto, precio=:precio, cantidad=:cantidad WHERE id = :id"); $query->bindParam(":codigo", $codigo); $query->bindParam(":producto", $producto); $query->bindParam(":precio", $precio); $query->bindParam(":cantidad", $cantidad); $query->bindParam(":id", $id); $query->execute(); echo "modificado"; $pdo = null; } } ?>
- Método Editar
<?php $data = json_decode(file_get_contents("php://input")); require "conexion.php"; $id = $data->id; $query = $pdo->prepare("SELECT * FROM productos WHERE id = :id"); $query->bindParam(":id", $id, PDO::PARAM_INT); $query->execute(); $result = $query->fetch(PDO::FETCH_ASSOC); echo json_encode($result); $pdo = null; ?>
- Método Eliminar
<?php $data = json_decode(file_get_contents("php://input")); $id = $data->id; require "conexion.php"; $eliminar = $pdo->prepare("DELETE FROM productos WHERE id = $id"); $eliminar->execute(); if ($eliminar) { echo "ok"; } ?>