<input type="text" id="nombre"> <input type="text" id="cantidad"> <input type="button" id="boton" value="Llamada ajax"> <div id="resultado"></div> <script> document.getElementById("boton").addEventListener("click", function () { var pepe = new XMLHttpRequest(); pepe.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { document.getElementById('resultado').innerHTML = this.responseText; } } var nombre=document.getElementById('nombre').value; var cantidad=document.getElementById('cantidad').value; pepe.open("GET", "datos.php?nombre="+nombre+"&cantidad="+cantidad); pepe.send(); }) </script>
Mes: julio 2018
Mantenimiento categorías
<!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <title>Mantenimiento categorías</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <?php require_once 'libreria.php'; $nombre = filter_input(INPUT_GET, 'nombre', FILTER_SANITIZE_STRING); $id = filter_input(INPUT_GET, 'idcategoria', FILTER_VALIDATE_INT); if (!empty($nombre)) { insertarCategoria($nombre); } if (!empty($id)) { borrarCategoria($id); } $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); $nombre = filter_input(INPUT_GET, 'categoria', FILTER_SANITIZE_STRING); if (!empty($id) && !empty($nombre)) { editarCategoria($id, $nombre); } ?> <h1>Mantenimiento categorías</h1> <form>Nombre: <input type="text" name="nombre"><input type="submit" class="btn btn-success"></form> <hr/> <?php listadoCategorias(); ?> </body> </html>
<!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <title>Editar categoría</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <?php require_once 'libreria.php'; $id = filter_input(INPUT_GET, 'idcategoria', FILTER_VALIDATE_INT); if(!empty($id)){ $categoria=getCategoria($id); } ?> <form action="categorias.php"> <input type="hidden" name="id" value="<?=$categoria['idcategorias']?>"> Nombre: <input type="text" name="categoria" value="<?=$categoria['nombre']?>"> <input type="submit" class="btn btn-success"> </form> <a href="categorias.php">Volver a categorías</a> </body> </html>
<?php function conectar() { $server = "localhost"; $user = "root"; $password = ""; $db = "tienda"; try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password, [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; } catch (Exception $ex) { echo $ex->getMessage(); } } function insertarCategoria($name) { try { $conn = conectar(); $st = $conn->prepare("insert into categorias (nombre) values (:name)"); $st->execute(['name' => $name]); } catch (Exception $ex) { echo $ex->getMessage(); } } function borrarCategoria($id) { try { $conn = conectar(); $st = $conn->prepare("delete from categorias where idcategorias=:id"); $st->execute(['id' => $id]); } catch (Exception $ex) { echo $ex->getMessage(); } } function editarCategoria($id,$nombre){ try{ $conn=conectar(); $st=$conn->prepare("update categorias set nombre=:nombre where idcategorias=:id"); $st->execute(['nombre'=>$nombre,'id'=>$id]); } catch (Exception $ex) { } } function getCategorias() { try { $conn = conectar(); $st = $conn->prepare("select * from categorias"); $st->execute(); $categorias = $st->fetchAll(); return $categorias; } catch (Exception $ex) { echo $ex->getMessage(); } } function getCategoria($id) { try { $conn = conectar(); $st = $conn->prepare("select * from categorias where idcategorias=:id"); $st->execute(['id' => $id]); $categoria = $st->fetch(); return $categoria; } catch (Exception $ex) { echo $ex->getMessage(); } } function listadoCategorias() { $categorias = getCategorias(); ?> <table class="table"> <tr><td>Id</td><td>Nombre</td><td>Acciones</td></tr> <?php foreach ($categorias as $categoria) { ?> <tr><td><?= $categoria['idcategorias'] ?></td> <td><?= $categoria['nombre'] ?></td> <td> <a href="?idcategoria=<?= $categoria['idcategorias'] ?>">Borrar</a> <a href="editar_categoria.php?idcategoria=<?= $categoria['idcategorias'] ?>">Editar</a> </td> </tr> <?php } ?> </table> <?php }
Categorías Sakila
<h1>Categorías</h1> <?php require_once 'libreria.php'; $category = filter_input(INPUT_GET, 'category', FILTER_SANITIZE_STRING); $category_id = filter_input(INPUT_GET, 'category_id', FILTER_VALIDATE_INT); if (!empty($category)) { insertarCategoria($category); } if(!empty($category_id)){ borraCategoria($category_id); } ?> <form> Categoría: <input type="text" name="category"> <input type="submit" class="btn btn-success"> </form> <hr/> <?php listadoCategorias(); ?>
libreria.php
<?php function conectar() { $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password, [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; } catch (Exception $ex) { echo $ex->getMessage(); } } function insertarCategoria($name) { try { $conn = conectar(); $st = $conn->prepare("insert into category (name) values (:name)"); $st->execute(['name' => $name]); } catch (Exception $ex) { echo $ex->getMessage(); } } function borraCategoria($id) { try { $conn = conectar(); $st = $conn->prepare("delete from category where category_id=:id"); $st->execute(['id' => $id]); } catch (Exception $ex) { echo $ex->getMessage(); } } function getCategorias() { try { $conn = conectar(); $st = $conn->prepare("select * from category"); $st->execute(); $categorias = $st->fetchAll(); return $categorias; } catch (Exception $ex) { echo $ex->getMessage(); } } function listadoCategorias() { echo "hola"; $categorias = getCategorias(); ?> <table class="table"> <tr><td>Id</td><td>Nombre</td><td>Acciones</td></tr> <?php foreach ($categorias as $categoria) { ?> <tr><td><?= $categoria['category_id'] ?></td> <td><?= $categoria['name'] ?></td> <td><a href="?category_id=<?= $categoria['category_id'] ?>">Borrar</a></td> </tr> <?php } ?> </table> <?php }
BD tienda
CREATE TABLE `tienda`.`categorias` ( `idcategorias` INT NOT NULL AUTO_INCREMENT, `nombre` VARCHAR(100) NOT NULL, PRIMARY KEY (`idcategorias`)); CREATE TABLE `tienda`.`productos` ( `idproductos` INT NOT NULL AUTO_INCREMENT, `nombre` VARCHAR(45) NULL, `precio` DECIMAL(6,4) NULL, `descripcion` VARCHAR(500) NULL, `idcategorias` INT NULL, PRIMARY KEY (`idproductos`), INDEX `fk_categorias_idx` (`idcategorias` ASC), CONSTRAINT `fk_categorias` FOREIGN KEY (`idcategorias`) REFERENCES `tienda`.`categorias` (`idcategorias`) ON DELETE RESTRICT ON UPDATE RESTRICT);
Como ver una página en navegadores antiguos
Función conectar
function conectar() { $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password,[PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; } catch (Exception $ex) { echo $ex->getMessage(); } }
Select con city
<?php $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); print_r($_GET); $address = filter_input(INPUT_GET, "address"); $district = filter_input(INPUT_GET, "district"); $city_id = filter_input(INPUT_GET, "city_id"); $postal_code = filter_input(INPUT_GET, "postal_code"); $phone = filter_input(INPUT_GET, "phone"); if(!empty($address) && !empty($district) &&!empty($city_id) && !empty($phone)){ $sql="insert into address (address,district,city_id,postal_code,phone) values "; $sql.="('$address','$district',$city_id,'$postal_code','$phone')"; $conn->exec($sql); } $sql = "select city_id,city from city order by city"; $resul = $conn->query($sql); $ciudades = $resul->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $ex) { echo $ex->getMessage(); } ?> <form> Dirección: <input type="text" name="address"><br/> Distrito: <input type="text" name="district"><br/> Ciudad: <select name="city_id"> <option value="0">Seleccione la ciudad</option> <?php foreach ($ciudades as $ciudad) { ?> <option value="<?= $ciudad['city_id'] ?>"><?= $ciudad['city'] ?></option> <?php } ?> </select><br/> Código postal: <input type="text" name="postal_code"><br/> Teléfono: <input type="text" name="phone"><br/> <input type="submit"> </form>
Galería de imágenes
<h1>Galería de imágenes</h1> <?php $borrar= filter_input(INPUT_GET, 'borrar'); if(!empty($borrar)){ unlink("images/".$borrar); } if (isset($_FILES['imagen'])) { if (explode("/", $_FILES['imagen']['type'])[0] == 'image') { move_uploaded_file($_FILES['imagen']['tmp_name'], "images/" . $_FILES['imagen']['name']); ?> <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>Ok</strong> El archivo se ha subido con éxito. </div> <?php } else { ?> <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>Error</strong> El archivo subido no es de tipo imagen. </div> <?php } } ?> <form action='index.php' method="post" enctype="multipart/form-data"> <input type="file" name="imagen" > <input type="submit" class="btn btn-success" value="Enviar imagen"> </form> <hr/> <div style='display:flex;flex-wrap: wrap;'> <?php $imagenes = scandir("./images"); for ($i = 2; $i < count($imagenes); $i++) { ?> <div class="card" style="width:400px" > <img class="card-img-top" src="images/<?= $imagenes[$i] ?>" alt="Card image"> <div class="card-body"> <h4 class="card-title"><?= $imagenes[$i] ?></h4> <a href="?borrar=<?= $imagenes[$i] ?>" class="btn btn-danger">Borrar imagen</a> </div> </div> <?php } ?> </div>
El hombre de la factura de 10000 dólares
CRUD actores Sakila
Index.php
<h1>Mantenimiento actores de Sakila</h1> <form> <input type="hidden" name="action" value="insert"> Nombre:<input type="text" name="first_name"> Apellidos:<input type="text" name="last_name"> <input type="submit" class="btn btn-info"> </form> <table class="table"> <tr><td>Id</td><td>Nombre</td><td>Apellidos</td><td>Acciones</td></tr> <?php $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; $action = filter_input(INPUT_GET, 'action'); $last_name = filter_input(INPUT_GET, 'last_name', FILTER_SANITIZE_STRING); $first_name = filter_input(INPUT_GET, 'first_name', FILTER_SANITIZE_STRING); $actor_id = filter_input(INPUT_GET, 'actor_id', FILTER_VALIDATE_INT); try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Acciones sobre la base de datos if ($action == 'insert' && !empty($first_name) && !empty($last_name)) { $sql = "insert into actor (first_name, last_name) values ('$first_name','$last_name')"; $conn->exec($sql); } if ($action == "delete" && !empty($actor_id)) { $sql = "delete from actor where actor_id=$actor_id"; $conn->exec($sql); } if ($action == 'update' && !empty($first_name) && !empty($last_name) && !empty($actor_id)) { $sql = "update actor set first_name='$first_name', last_name='$last_name' where actor_id=$actor_id"; $conn->exec($sql); } $sql = "select * from actor"; $resul = $conn->query($sql); while ($fila = $resul->fetch(PDO::FETCH_ASSOC)) { ?> <tr><td><?= $fila['actor_id'] ?></td> <td><?= $fila['first_name'] ?></td> <td><?= $fila['last_name'] ?></td> <td><a href="?action=delete&actor_id=<?= $fila['actor_id'] ?>">Borrar</a> <a href="update.php?actor_id=<?= $fila['actor_id'] ?>">Editar</a></td></tr> <?php } } catch (Exception $ex) { echo "Ha ocurrido un error<br/>" . $ex->getMessage(); } ?></table>
update.php
<h1>Editar actor</h1> <?php $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; $actor_id = filter_input(INPUT_GET, 'actor_id', FILTER_VALIDATE_INT); if (!empty($actor_id)) { try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "select * from actor where actor_id=$actor_id"; $resul=$conn->query($sql); $fila=$resul->fetch(); } catch (Exception $ex) { echo "Ha ocurrido un error<br/>" . $ex->getMessage(); } } ?> <form action="index.php"> <input type="hidden" name="action" value="update"> <input type="hidden" name="actor_id" value="<?=$actor_id?>"> Nombre:<input type="text" name="first_name" value="<?=$fila['first_name']?>"> Apellidos:<input type="text" name="last_name" value="<?=$fila['last_name']?>"> <input type="submit" class="btn btn-info"> </form>
final.php
<h1>Consulta actores de Sakila</h1> <form> Nombre:<input type="text" name="first_name"> Apellidos:<input type="text" name="last_name"> <input type="submit" class="btn btn-info" value="Buscar"> </form> <table class="table"> <tr><td>Id</td><td>Nombre</td><td>Apellidos</td></tr> <?php $server = "localhost"; $user = "root"; $password = ""; $db = "sakila"; $last_name = filter_input(INPUT_GET, 'last_name', FILTER_SANITIZE_STRING); $first_name = filter_input(INPUT_GET, 'first_name', FILTER_SANITIZE_STRING); try { $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "select * from actor where 1"; if (!empty($first_name)){ $sql.=" and first_name like '%$first_name%'"; } if (!empty($last_name)){ $sql.=" and last_name like '%$last_name%'"; } $resul = $conn->query($sql); while ($fila = $resul->fetch(PDO::FETCH_ASSOC)) { ?> <tr><td><?= $fila['actor_id'] ?></td> <td><?= $fila['first_name'] ?></td> <td><?= $fila['last_name'] ?></td> </tr> <?php } } catch (Exception $ex) { echo "Ha ocurrido un error<br/>" . $ex->getMessage(); } ?></table>