He recibido muchas peticiones de mis lectores para crear galería de imágenes con la posibilidad de que dicha galería tenga un panel de administración en donde el usuario podrá: ver, crear, editar y eliminar las imágenes; así como actualizar el texto del título y la descripción de dichas imágenes, por lo que en este tutorial voy a mostrar cómo crear una galería de imágenes con bootstrap, php y mysql. Usando un fragmento de código desde bootsnipp se ha creado un galería muy fácil de entender, con PHP y MySQL haremos que la carga de las imágenes sea dinámica.
Galería de imágenes con Bootstrap, PHP y MySQL
¿Qué es lo que haremos?
Diseño de la base de datos: Para este ejemplo hemos creado una base de datos llamada test_gallery la cual tiene la estructura siguiente, para hacer funcional este script, se deberá crear manualmente la base de datos MySQL, luego ejecutar la consulta siguiente en la base de datos que hemos creado.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 14-06-2017 a las 04:35:29 -- Versión del servidor: 10.1.19-MariaDB -- Versión de PHP: 7.0.13 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `test_gallery` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `banner` -- CREATE TABLE `banner` ( `id` int(11) NOT NULL, `titulo` varchar(50) NOT NULL, `descripcion` varchar(255) NOT NULL, `url_image` varchar(255) NOT NULL, `estado` int(1) NOT NULL, `orden` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `banner` -- INSERT INTO `banner` (`id`, `titulo`, `descripcion`, `url_image`, `estado`, `orden`) VALUES (1, 'Sistema Web de Inventario Simple ', 'https://obedalvarado.pw/blog/sistema-inventario-simple-php/', 'simple_stock_php.png', 1, 1), (2, 'Sistema de Facturación Simple', 'http://obedalvarado.pw/simple-invoice/', 'factura_simple.png', 1, 2), (17, 'Cómo instalar ionCube Loader en Windows', 'En este tutorial voy a mostrar como instalar ioncube loader en servidor local con Windows.', 'ioncube-windows.png', 1, 3), (18, 'Importando datos Excel a una base de datos MySQL c', 'Muchas aplicaciones PHP necesitan procesar archivos Excel, para distintos propósitos, lo más común es importar datos desde un archivo e insertarlos en una base de datos.', 'excel_mysql.png', 1, 4), (19, 'CRUD de datos de empleados con PHP, MySQL y Bootst', 'La creación de un CRUD es una tarea muy común en el desarrollo web (CRUD por sus siglas en ingles Create/Read/Update/Delete). ', 'crud_empleados.png', 1, 5), (20, 'SISTEMA PARA FARMACIAS DESARROLLADO CON PHP – MY', 'El sistema de Inventario para farmacias es un software de oficina de farmacia, que cuenta con un diseño moderno de respuesta ideal para cualquier tipo de negocio de farmacia.', 'inventario_farmacia.png', 1, 6), (21, 'Cotizador web de camisetas con PHP', 'En esta ocasión quiero compartir un pequeño script desarrollado en PHP, el cual cumple la función de cotizador web de productos', 'captura_1.png', 1, 7), (22, 'Sistema de Gestión de Inventario con PHP', 'El Sistema de Gestión de Inventario es un proyecto de código abierto (Open Source), desarrollado con PHP, MySQL, Bootstrap y jQuery.', 'sistema_gestion_inventario_php.png', 1, 8); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `banner` -- ALTER TABLE `banner` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `banner` -- ALTER TABLE `banner` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; |
Conexión a la base de datos: Para conectarnos a la base de datos creada en el paso anterior debemos editar el archivo “conexion.php”, y luego colocar los datos de conexión según corresponda a nuestro servidor de base de datos.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $DB_HOST="localhost"; $DB_NAME= "test_gallery"; $DB_USER= "root"; $DB_PASS= ""; # conectare la base de datos $con=@mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); if(!$con){ die("imposible conectarse: ".mysqli_error($con)); } if (@mysqli_connect_errno()) { die("Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error()); } ?> |
Archivo index.php: El archivo index.php contiene el código necesario para poder mostrar nuestras la galería de imágenes, las cuales son cargadas de forma dinámica desde nuestra base de datos MySQL.
Administración de la Galería de Imágenes
Para la administración de la galería de imágenes se ha creado un directorio llamado “admin”, y dentro de dicho directorio el archivo bannerlist.php, el cual hace de una llamada al archivo ajax/banner_ajax.php, el código es el siguiente:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
<?php $title="Galería de imágenes"; /* Llamar la Cadena de Conexion*/ include ("../conexion.php"); $active_config="active"; $active_banner="active"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../images/ico/favicon.ico"> <title><?php echo $title;?></title> <!-- Bootstrap core CSS --> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Custom styles for this template --> <link href="css/navbar-fixed-top.css" rel="stylesheet"> </head> <body> <?php include("top_menu.php");?> <div class="container"> <!-- Main component for a primary marketing message or call to action --> <div class="row"> <ol class="breadcrumb"> <li><a href="#">Inicio</a></li> <li class="active">Banner</li> </ol> <div class="row"> <div class="col-xs-12 text-right"> <a href='banneradd.php' class="btn btn-default" ><span class="glyphicon glyphicon-plus"></span> Agregar Banner</a> </div> </div> <br> <div id="loader" class="text-center"> <span><img src="./img/ajax-loader.gif"></span></div> <div class="outer_div"></div><!-- Datos ajax Final --> </div> </div> <!-- /container --> <?php include("footer.php");?> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </body> </html> <script> $(document).ready(function(){ load(1); }); function load(page){ var parametros = {"action":"ajax","page":page}; $.ajax({ url:'./ajax/banner_ajax.php', data: parametros, beforeSend: function(objeto){ $("#loader").html("<img src='../img/ajax-loader.gif'>"); }, success:function(data){ $(".outer_div").html(data).fadeIn('slow'); $("#loader").html(""); } }) } function eliminar_slide(id){ page=1; var parametros = {"action":"ajax","page":page,"id":id}; if(confirm('Esta acción eliminará de forma permanente el banner \n\n Desea continuar?')){ $.ajax({ url:'./ajax/banner_ajax.php', data: parametros, beforeSend: function(objeto){ $("#loader").html("<img src='../images/ajax-loader.gif'>"); }, success:function(data){ $(".outer_div").html(data).fadeIn('slow'); $("#loader").html(""); } }) } } </script> |
Archivo ajax/banner_ajax.php: Se encarga de procesar las peticiones recibidas vía ajax desde el archivo creado en el paso anterior. La funcionalidad de dicho archivo es la de listar las imágenes previamente cargadas a nuestra base de datos.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
<?php session_start(); /* Llamar la Cadena de Conexion*/ include ("../../conexion.php"); $action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:''; if($action == 'ajax'){ //Elimino producto if (isset($_REQUEST['id'])){ $id_banner=intval($_REQUEST['id']); if ($delete=mysqli_query($con,"delete from banner where id='$id_banner'")){ $message= "Datos eliminados satisfactoriamente"; } else { $error= "No se pudo eliminar los datos"; } } $tables="banner"; $sWhere=" "; $sWhere.=" "; $sWhere.=" order by id"; include 'pagination.php'; //include pagination file //pagination variables $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1; $per_page = 12; //how much records you want to show $adjacents = 4; //gap between pages after number of adjacents $offset = ($page - 1) * $per_page; //Count the total number of row in your table*/ $count_query = mysqli_query($con,"SELECT count(*) AS numrows FROM $tables $sWhere "); if ($row= mysqli_fetch_array($count_query)) { $numrows = $row['numrows']; } else {echo mysqli_error($con);} $total_pages = ceil($numrows/$per_page); $reload = './productslist.php'; //main query to fetch the data $query = mysqli_query($con,"SELECT * FROM $tables $sWhere LIMIT $offset,$per_page"); if (isset($message)){ ?> <div class="alert alert-success alert-dismissible fade in" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>Aviso!</strong> <?php echo $message;?> </div> <?php } if (isset($error)){ ?> <div class="alert alert-danger alert-dismissible fade in" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>Error!</strong> <?php echo $error;?> </div> <?php } //loop through fetched data if ($numrows>0) { ?> <div class="row"> <?php while($row = mysqli_fetch_array($query)){ $url_image=$row['url_image']; $titulo=$row['titulo']; $id_slide=$row['id']; ?> <div class="col-sm-6 col-md-3"> <div class="thumbnail"> <img src="../img/banner/<?php echo $url_image;?>" alt="..."> <div class="caption"> <h3><?php echo $titulo;?></h3> <p class='text-right'><a href="banneredit.php?id=<?php echo intval($id_slide);?>" class="btn btn-info" role="button"><i class='glyphicon glyphicon-edit'></i> Editar</a> <button type="button" class="btn btn-danger" onclick="eliminar_slide('<?php echo $id_slide;?>');" role="button"><i class='glyphicon glyphicon-trash'></i> Eliminar</button></p> </div> </div> </div> <?php } ?> </div> <div class="table-pagination text-right"> <?php echo paginate($reload, $page, $total_pages, $adjacents);?> </div> <?php } } ?> |
Paginar registros: el archivo “ajax/pagination.php” contiene una función que se encargará de paginar los registros usando ajax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<?php function paginate($reload, $page, $tpages, $adjacents) { $prevlabel = "‹ Prev"; $nextlabel = "Next ›"; $out = '<ul class="pagination pagination-large">'; // previous label if($page==1) { $out.= "<li class='disabled'><span><a>$prevlabel</a></span></li>"; } else if($page==2) { $out.= "<li><span><a href='javascript:void(0);' onclick='load(1)'>$prevlabel</a></span></li>"; }else { $out.= "<li><span><a href='javascript:void(0);' onclick='load(".($page-1).")'>$prevlabel</a></span></li>"; } // first label if($page>($adjacents+1)) { $out.= "<li><a href='javascript:void(0);' onclick='load(1)'>1</a></li>"; } // interval if($page>($adjacents+2)) { $out.= "<li><a>...</a></li>"; } // pages $pmin = ($page>$adjacents) ? ($page-$adjacents) : 1; $pmax = ($page<($tpages-$adjacents)) ? ($page+$adjacents) : $tpages; for($i=$pmin; $i<=$pmax; $i++) { if($i==$page) { $out.= "<li class='active'><a>$i</a></li>"; }else if($i==1) { $out.= "<li><a href='javascript:void(0);' onclick='load(1)'>$i</a></li>"; }else { $out.= "<li><a href='javascript:void(0);' onclick='load(".$i.")'>$i</a></li>"; } } // interval if($page<($tpages-$adjacents-1)) { $out.= "<li><a>...</a></li>"; } // last if($page<($tpages-$adjacents)) { $out.= "<li><a href='javascript:void(0);' onclick='load($tpages)'>$tpages</a></li>"; } // next if($page<$tpages) { $out.= "<li><span><a href='javascript:void(0);' onclick='load(".($page+1).")'>$nextlabel</a></span></li>"; }else { $out.= "<li class='disabled'><span><a>$nextlabel</a></span></li>"; } $out.= "</ul>"; return $out; } ?> |
Creación del archivo top_menu.php: Siempre dentro de nuestra carpeta de administración “admin”, debemos crear un archivo llamado “top_menu.php”, el cual contiene un pequeño menú de nuestra aplicación.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!-- Fixed navbar --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"></a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="bannerlist.php"><i class='glyphicon glyphicon-film'></i> Galería</a></li> <li><a href="../" target="_blank"><i class='glyphicon glyphicon-blackboard'></i> Ver sitio</a></li> </ul> </li> </div> </nav> |
El archivo footer.php: Este archivo se encuentra en la carpeta admin y contiene los créditos del auto 😀
1 2 3 4 5 |
<footer class="footer"> <div class="container"> <p class="text-muted">Desarrollado por <a href="http://obedalvarado.pw/" target='_blank'>Obed Alvarado</a></p> </div> </footer> |
Cargando una nueva imagen al servidor: para cargar una imagen al servidor hemos creado un archivo llamado “banneradd.php” , el cual se debe crear dentro de la carpeta admin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
<?php session_start(); $title="Agregar Banner"; /* Llamar la Cadena de Conexion*/ include ("../conexion.php"); //Insert un nuevo producto $imagen_demo="demo.png"; $insert=mysqli_query($con,"insert into banner (url_image, estado) values ('$imagen_demo','0')"); $sql_last=mysqli_query($con,"select LAST_INSERT_ID(id) as last from banner order by id desc limit 0,1"); $rw=mysqli_fetch_array($sql_last); $id_banner=intval($rw['last']); $sql=mysqli_query($con,"select * from banner where id='$id_banner' limit 0,1"); $count=mysqli_num_rows($sql); if ($count==0){ //header("location: bannerlist.php"); //exit; } $rw=mysqli_fetch_array($sql); $titulo=$rw['titulo']; $descripcion=$rw['descripcion']; $url_image=$rw['url_image']; $orden=intval($rw['orden']); $estado=intval($rw['estado']); $active_config="active"; $active_banner="active"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../images/ico/favicon.ico"> <title><?php echo $title;?></title> <!-- Bootstrap core CSS --> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Custom styles for this template --> <link href="css/navbar-fixed-top.css" rel="stylesheet"> <link href="css/preview-image.css" rel="stylesheet"> </head> <body> <?php include("top_menu.php");?> <div class="container"> <!-- Main component for a primary marketing message or call to action --> <div class="row"> <ol class="breadcrumb"> <li><a href="#">Inicio</a></li> <li><a href="bannerlist.php">Banner</a></li> <li class="active">Editar</li> </ol> <div class="col-md-7"> <h3 ><span class="glyphicon glyphicon-edit"></span> Editar banner</h3> <form class="form-horizontal" id="editar_banner"> <div class="form-group"> <label for="titulo" class="col-sm-3 control-label">Titulo</label> <div class="col-sm-9"> <input type="text" class="form-control" id="titulo" value="<?php echo $titulo;?>" required name="titulo"> <input type="hidden" class="form-control" id="id_banner" value="<?php echo intval($id_banner);?>" name="id_banner"> </div> </div> <div class="form-group"> <label for="titulo" class="col-sm-3 control-label">Descripción</label> <div class="col-sm-9"> <textarea class='form-control' name="descripcion" id="descripcion" required rows=8><?php echo $descripcion;?></textarea> </div> </div> <div class="form-group"> <label for="orden" class="col-sm-3 control-label">Orden</label> <div class="col-sm-9"> <input type="number" class="form-control" id="orden" name="orden" value="<?php echo $orden;?>"> </div> </div> <div class="form-group"> <label for="estado" class="col-sm-3 control-label">Estado</label> <div class="col-sm-9"> <select class="form-control" id="estado" required name="estado"> <option value="0" <?php if($estado==0){echo "selected";} ?>>Inactivo</option> <option value="1" <?php if($estado==1){echo "selected";} ?>>Activo</option> </select> </div> </div> <div class="form-group"> <div id='loader'></div> <div class='outer_div'></div> <div class="col-sm-offset-3 col-sm-9"> <button type="submit" class="btn btn-success">Actualizar datos</button> </div> </div> </form> </div> <div class="col-md-5"> <h3 ><span class="glyphicon glyphicon-picture"></span> Imagen</h3> <form class="form-vertical"> <div class="form-group"> <div class="col-sm-12"> <div class="fileinput fileinput-new" data-provides="fileinput"> <div class="fileinput-new thumbnail" style="max-width: 100%;" > <img class="img-rounded" src="../img/banner/<?php echo $url_image;?>" /> </div> <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 250px; max-height: 250px;"></div> <div> <span class="btn btn-info btn-file"><span class="fileinput-new">Selecciona una imagen</span> <span class="fileinput-exists" onclick="upload_image();">Cambiar imagen</span><input type="file" name="fileToUpload" id="fileToUpload" required onchange="upload_image();"></span> <a href="#" class="btn btn-danger fileinput-exists" data-dismiss="fileinput">Cancelar</a> </div> </div> <div class="upload-msg"></div> </div> </div> </form> </div> </div> </div><!-- /container --> <?php include("footer.php");?> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script src="js/jasny-bootstrap.min.js"></script> </body> </html> <script> function upload_image(){ $(".upload-msg").text('Cargando...'); var id_banner=$("#id_banner").val(); var inputFileImage = document.getElementById("fileToUpload"); var file = inputFileImage.files[0]; var data = new FormData(); data.append('fileToUpload',file); data.append('id',id_banner); $.ajax({ url: "ajax/upload_banner.php", // Url to which the request is send type: "POST", // Type of request to be send, called as method data: data, // Data sent to server, a set of key/value pairs (i.e. form fields and values) contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData:false, // To send DOMDocument or non processed data file it is set to false success: function(data) // A function to be called if request succeeds { $(".upload-msg").html(data); window.setTimeout(function() { $(".alert-dismissible").fadeTo(500, 0).slideUp(500, function(){ $(this).remove(); }); }, 5000); } }); } function eliminar(id){ var parametros = {"action":"delete","id":id}; $.ajax({ url:'ajax/upload2.php', data: parametros, beforeSend: function(objeto){ $(".upload-msg2").text('Cargando...'); }, success:function(data){ $(".upload-msg2").html(data); } }) } </script> <script> $("#editar_banner").submit(function(e) { $.ajax({ url: "ajax/editar_banner.php", type: "POST", data: $("#editar_banner").serialize(), beforeSend: function(objeto){ $("#loader").html("Cargando..."); }, success:function(data){ $(".outer_div").html(data).fadeIn('slow'); $("#loader").html(""); } }); e.preventDefault(); }); </script> |
El archivo creado anteriormente hace dos peticiones vía ajax:
- Para cargar una imagen
- Para registrar datos relacionados a la imagen en la base de datos MySQL
Creación del archivo ajax/upload_banner.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
<?php if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_FILES["fileToUpload"]["type"])){ /* Llamar la Cadena de Conexion*/ include ("../../conexion.php"); $id_banner=intval($_POST['id']); $target_dir = "../../img/banner/"; $carpeta=$target_dir; if (!file_exists($carpeta)) { mkdir($carpeta, 0777, true); } $target_file = $carpeta . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { $errors[]= "El archivo es una imagen - " . $check["mime"] . "."; $uploadOk = 1; } else { $errors[]= "El archivo no es una imagen."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { $errors[]="Lo sentimos, archivo ya existe."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 524288) { $errors[]= "Lo sentimos, el archivo es demasiado grande. Tamaño máximo admitido: 0.5 MB"; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { $errors[]= "Lo sentimos, sólo archivos JPG, JPEG, PNG & GIF son permitidos."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { $errors[]= "Lo sentimos, tu archivo no fue subido."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { $messages[]= "El Archivo ha sido subido correctamente."; $ruta=$_FILES["fileToUpload"]["name"]; $update=mysqli_query($con,"UPDATE banner SET url_image='$ruta' WHERE id='$id_banner'"); } else { $errors[]= "Lo sentimos, hubo un error subiendo el archivo."; } } if (isset($errors)){ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>Error!</strong> <?php foreach ($errors as $error){ echo"<p>$error</p>"; } ?> </div> <?php } if (isset($messages)){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>Aviso!</strong> <?php foreach ($messages as $message){ echo"<p>$message</p>"; } ?> </div> <?php } } ?> |
Creación del archivo ajax/editar_banner.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<?php session_start(); if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST["titulo"])){ /* Llamar la Cadena de Conexion*/ include ("../../conexion.php"); // escaping, additionally removing everything that could be (html/javascript-) code $titulo = mysqli_real_escape_string($con,(strip_tags($_POST['titulo'], ENT_QUOTES))); $descripcion = mysqli_real_escape_string($con,($_POST['descripcion'])); $orden = intval($_POST['orden']); $estado = intval($_POST['estado']); $id_banner=intval($_POST['id_banner']); $sql="UPDATE banner SET titulo='$titulo', descripcion='$descripcion', orden='$orden', estado='$estado' WHERE id='$id_banner'"; $query = mysqli_query($con,$sql); // if user has been added successfully if ($query) { $messages[] = "Datos han sido actualizados satisfactoriamente."; } else { $errors []= "Lo siento algo ha salido mal intenta nuevamente.".mysqli_error($con); } if (isset($errors)){ ?> <div class="alert alert-danger" role="alert"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>Error!</strong> <?php foreach ($errors as $error) { echo $error; } ?> </div> <?php } if (isset($messages)){ ?> <div class="alert alert-success" role="alert"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>¡Bien hecho!</strong> <?php foreach ($messages as $message) { echo $message; } ?> </div> <?php } } ?> |
Editando las imágenes: Para editar las imágenes, así como el contenido relacionado a las imágenes se ha creado el archivo “banneredit.php”, dicho archivo se encarga de mostrar un formulario con el titulo, descripción, orden y estado de la imagen; y por supuesto que también muestra la imagen que se esta editando.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
<?php session_start(); $title="Editar Banner"; /* Llamar la Cadena de Conexion*/ include ("../conexion.php"); //Insert un nuevo producto $imagen_demo="demo.png"; $id_banner=intval($_GET['id']); $sql=mysqli_query($con,"select * from banner where id='$id_banner' limit 0,1"); $count=mysqli_num_rows($sql); if ($count==0){ //header("location: bannerlist.php"); //exit; } $rw=mysqli_fetch_array($sql); $titulo=$rw['titulo']; $descripcion=$rw['descripcion']; $url_image=$rw['url_image']; $orden=intval($rw['orden']); $estado=intval($rw['estado']); $active_config="active"; $active_banner="active"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../images/ico/favicon.ico"> <title><?php echo $title;?></title> <!-- Bootstrap core CSS --> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Custom styles for this template --> <link href="css/navbar-fixed-top.css" rel="stylesheet"> <link href="css/preview-image.css" rel="stylesheet"> </head> <body> <?php include("top_menu.php");?> <div class="container"> <!-- Main component for a primary marketing message or call to action --> <div class="row"> <ol class="breadcrumb"> <li><a href="#">Inicio</a></li> <li><a href="bannerlist.php">Banner</a></li> <li class="active">Editar</li> </ol> <div class="col-md-7"> <h3 ><span class="glyphicon glyphicon-edit"></span> Editar banner</h3> <form class="form-horizontal" id="editar_banner"> <div class="form-group"> <label for="titulo" class="col-sm-3 control-label">Titulo</label> <div class="col-sm-9"> <input type="text" class="form-control" id="titulo" value="<?php echo $titulo;?>" required name="titulo"> <input type="hidden" class="form-control" id="id_banner" value="<?php echo intval($id_banner);?>" name="id_banner"> </div> </div> <div class="form-group"> <label for="titulo" class="col-sm-3 control-label">Descripción</label> <div class="col-sm-9"> <textarea class='form-control' name="descripcion" id="descripcion" required rows=8><?php echo $descripcion;?></textarea> </div> </div> <div class="form-group"> <label for="orden" class="col-sm-3 control-label">Orden</label> <div class="col-sm-9"> <input type="number" class="form-control" id="orden" name="orden" value="<?php echo $orden;?>"> </div> </div> <div class="form-group"> <label for="estado" class="col-sm-3 control-label">Estado</label> <div class="col-sm-9"> <select class="form-control" id="estado" required name="estado"> <option value="0" <?php if($estado==0){echo "selected";} ?>>Inactivo</option> <option value="1" <?php if($estado==1){echo "selected";} ?>>Activo</option> </select> </div> </div> <div class="form-group"> <div id='loader'></div> <div class='outer_div'></div> <div class="col-sm-offset-3 col-sm-9"> <button type="submit" class="btn btn-success">Actualizar datos</button> </div> </div> </form> </div> <div class="col-md-5"> <h3 ><span class="glyphicon glyphicon-picture"></span> Imagen</h3> <form class="form-vertical"> <div class="form-group"> <div class="col-sm-12"> <div class="fileinput fileinput-new" data-provides="fileinput"> <div class="fileinput-new thumbnail" style="max-width: 100%;" > <img class="img-rounded" src="../img/banner/<?php echo $url_image;?>" /> </div> <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 250px; max-height: 250px;"></div> <div> <span class="btn btn-info btn-file"><span class="fileinput-new">Selecciona una imagen</span> <span class="fileinput-exists" onclick="upload_image();">Cambiar imagen</span><input type="file" name="fileToUpload" id="fileToUpload" required onchange="upload_image();"></span> <a href="#" class="btn btn-danger fileinput-exists" data-dismiss="fileinput">Cancelar</a> </div> </div> <div class="upload-msg"></div> </div> </div> </form> </div> </div> </div><!-- /container --> <?php include("footer.php");?> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script src="js/jasny-bootstrap.min.js"></script> </body> </html> <script> function upload_image(){ $(".upload-msg").text('Cargando...'); var id_banner=$("#id_banner").val(); var inputFileImage = document.getElementById("fileToUpload"); var file = inputFileImage.files[0]; var data = new FormData(); data.append('fileToUpload',file); data.append('id',id_banner); $.ajax({ url: "ajax/upload_banner.php", // Url to which the request is send type: "POST", // Type of request to be send, called as method data: data, // Data sent to server, a set of key/value pairs (i.e. form fields and values) contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData:false, // To send DOMDocument or non processed data file it is set to false success: function(data) // A function to be called if request succeeds { $(".upload-msg").html(data); window.setTimeout(function() { $(".alert-dismissible").fadeTo(500, 0).slideUp(500, function(){ $(this).remove(); }); }, 5000); } }); } function eliminar(id){ var parametros = {"action":"delete","id":id}; $.ajax({ url:'ajax/upload2.php', data: parametros, beforeSend: function(objeto){ $(".upload-msg2").text('Cargando...'); }, success:function(data){ $(".upload-msg2").html(data); } }) } </script> <script> $("#editar_banner").submit(function(e) { $.ajax({ url: "ajax/editar_banner.php", type: "POST", data: $("#editar_banner").serialize(), beforeSend: function(objeto){ $("#loader").html("Cargando..."); }, success:function(data){ $(".outer_div").html(data).fadeIn('slow'); $("#loader").html(""); } }); e.preventDefault(); }); </script> |
Este código podría ser útil para los desarrolladores o diseñadores web que deseen una solución rápida para mostrar galerías de imágenes en cualquier sitio web. Te invito a que descargues el código completo mostrado a continuacion o que eches un vistazo a la demostración.
Demostración frontend Demostración backend Descargar