A continuación vamos crear una aplicación con mysql y php en la cual vamos a subir un producto mediante un formulario en cual de además de insertar sus características del producto vamos a poder subir una imagen del producto y posteriormente vamos poder visualizarla mediante una búsqueda y mostrarla en una paginador.
Comenzamos por crear nuestra base de datos con mysql escribimos el siguiente query:
CREATE DATABASE productdb CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE TABLE IF NOT EXISTS `producto` ( `idproducto` INT NOT NULL AUTO_INCREMENT, `nombreProducto` VARCHAR(200) NOT NULL, `descripcion` VARCHAR(500) NOT NULL, `precio` FLOAT NOT NULL, `anchuraImagen` INT NOT NULL, `alturaImagen` INT NOT NULL, `tipoImagen` VARCHAR(15) NOT NULL, `imagen` LONGBLOB NOT NULL, PRIMARY KEY (`idproducto`, `nombreProducto`)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;
Una vez creada nuestra base de datos creamos una archivo config.php para poder conectranos a la base de datos y realizar todos querys necesarios para poder interactuar con la base de datos, escribimos el siguiente código:
<?php
$con = mysql_connect('localhost', 'root', 'lara') or die ('error: no se pudo conectar a mysql');
$database = 'productdb';
?>
Ahora realizamos nuestro formulario de captura y creamos el archivo index.php. Vamos a utilizar jquery validation para validar nuestro formulario.Al ultimo compartiremos el código funcional de este ejemplo.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>
<title>product form</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<a href="producto.php">Buscar producto</a>
<div class="contenido">
<h1>Product Form</h1>
<form id="form1" action="index.php" method="post" novalidate enctype="multipart/form-data">
<fieldset>
<legend>Introduce los datos de tu producto en el siguiente formulario</legend>
<label for="nombreProducto">Nombre del producto:</label>
<input type="text" name="nombreProducto" id="nombreProducto">
<div class="clear"> </div>
<label for="descripcion">Descripción:</label>
<textarea rows="10" cols="30" name="descripcion" id="descripcion"></textarea>
<div class="clear"> </div>
<label for="precio">Precio:</label>
<input type="text" name="precio" id="precio">
<div class="clear"> </div>
<label for="imagen">Subir imagen:</label>
<input type="file" name="imagen" id="imagen" />
<div class="clear"> </div>
<input type="submit" class="enviar" name="enviar" id="enviar" value="subir producto" />
</fieldset>
</form>
</div>
<script src="js/jquery.js"></script>
<script src="js/jquery.validate.js"></script>
<script src="js/additional-methods.js"></script>
<script src="js/messages_es.js"></script>
<script>
$("#form1").validate({
rules: {
nombreProducto: {
required: true
},
descripcion: {
required: true
},
precio: {
required: true,
number: true
},
imagen: {
required: true,
extension: "png|jpe?g|gif"
},
},
submitHandler: function(form) {
form.submit();
//alert("producto enviado");
}
});
</script>
<?php
if ( ! empty( $_POST ) ) {
include("config.php");
mysql_select_db("$database",$con);
# Comprovamos que se haya subido un fichero
if (is_uploaded_file($_FILES["imagen"]["tmp_name"]))
{
# Cogemos la anchura y altura de la imagen
$info=getimagesize($_FILES["imagen"]["tmp_name"]);
//echo "<BR>".$info[0]; //anchura
//echo "<BR>".$info[1]; //altura
$imagenBinaria = addslashes(file_get_contents($_FILES['imagen']['tmp_name']));
mysql_query(" INSERT INTO producto VALUES(null,'".$_POST["nombreProducto"]."','".$_POST["descripcion"]."',".$_POST["precio"].",".$info[0].",".$info[1].",'".$_FILES["imagen"]["type"]."','".$imagenBinaria."') ",$con);
}
}
?>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>
<title>product form</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<a href="index.php">Agregar Producto</a>
<div class="contenido">
<h1>Product Form</h1>
<form id="form1" action="producto.php" method="post" novalidate enctype="multipart/form-data">
<fieldset>
<legend>Buscar producto</legend>
<label for="nombreProducto">Buscar:</label>
<input type="text" name="producto" id="producto" size="70">
<input type="submit" class="buscar" name="buscar" id="buscar" value="buscar"/>
</fieldset>
</form>
</div>
<div class="paging"></div>
<?php
if ( ! empty( $_POST ) ) {
include("config.php");
mysql_select_db("$database",$con);
$results = mysql_query("SELECT * FROM producto WHERE nombreProducto LIKE '%".$_POST["producto"]."%'",$con);
while($row = mysql_fetch_assoc($results)){
?>
<div class="element">
<hr>
<table>
<tr>
<td>
<img src="data:<?php echo $row['tipoImagen']; ?>;base64,<?php echo base64_encode($row['imagen']); ?>" height="160" width="213" /><br>
</td>
<td>
ID Producto: <?php echo $row['idproducto']; ?><br>
Producto: <?php echo $row['nombreProducto']; ?><br>
Descripción: <?php echo $row['descripcion']; ?><br>
Precio: $<?php echo $row['precio']; ?><br>
</td>
</tr>
</table>
<hr>
</div>
<?php
}
}
?>
<div class="paging"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="js/jquery.ba-hashchange.js"></script>
<script src="js/jquery.paging.min.js"></script>
<script>
/*
* Slicing the content with two pagers and using the URL Hash event
*/
(function() {
var prev = {
start: 0,
stop: 0
};
var content = $('.element');
var Paging = $(".paging").paging(content.length, {
onSelect: function() {
var data = this.slice;
content.slice(prev[0], prev[1]).css('display', 'none');
content.slice(data[0], data[1]).fadeIn("slow");
prev = data;
return true; // locate!
},
onFormat: function(type) {
switch (type) {
case 'block':
if (!this.active)
return '<span class="disabled">' + this.value + '</span>';
else if (this.value != this.page)
return '<em><a href="#' + this.value + '">' + this.value + '</a></em>';
return '<span class="current">' + this.value + '</span>';
case 'right':
case 'left':
if (!this.active) {
return '';
}
return '<a href="#' + this.value + '">' + this.value + '</a>';
case 'next':
if (this.active) {
return '<a href="#' + this.value + '" class="next">Next »</a>';
}
return '<span class="disabled">Next »</span>';
case 'prev':
if (this.active) {
return '<a href="#' + this.value + '" class="prev">« Previous</a>';
}
return '<span class="disabled">« Previous</span>';
case 'first':
if (this.active) {
return '<a href="#' + this.value + '" class="first">|<</a>';
}
return '<span class="disabled">|<</span>';
case 'last':
if (this.active) {
return '<a href="#' + this.value + '" class="prev">>|</a>';
}
return '<span class="disabled">>|</span>';
case 'fill':
if (this.active) {
return "...";
}
}
return ""; // return nothing for missing branches
},
format: '[< ncnnn! >]',
perpage: 3,
lapping: 0,
page: null // we await hashchange() event
});
$(window).hashchange(function() {
if (window.location.hash)
Paging.setPage(window.location.hash.substr(1));
else
Paging.setPage(1); // we dropped "page" support and need to run it by hand
});
$(window).hashchange();
})();
</script>
</body>
</html>
<?php
$cons_usuario="root";
$cons_contra="lara";
$cons_base_datos="productdb";
$cons_equipo="localhost";
$obj_conexion = mysqli_connect($cons_equipo,$cons_usuario,$cons_contra,$cons_base_datos);
if(!$obj_conexion)
{
echo "<h3>No se ha podido conectar PHP - MySQL, verifique sus datos.</h3><hr><br>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>
<title>product form</title>
<link rel="stylesheet" type="text/css" href="../css/style.css" />
</head>
<body>
<a href="producto.php">Buscar producto</a>
<div class="contenido">
<h1>Product Form</h1>
<form id="form1" action="index.php" method="post" novalidate enctype="multipart/form-data">
<fieldset>
<legend>Introduce los datos de tu producto en el siguiente formulario</legend>
<label for="nombreProducto">Nombre del producto:</label>
<input type="text" name="nombreProducto" id="nombreProducto">
<div class="clear"> </div>
<label for="descripcion">Descripción:</label>
<textarea rows="10" cols="30" name="descripcion" id="descripcion"></textarea>
<div class="clear"> </div>
<label for="precio">Precio:</label>
<input type="text" name="precio" id="precio">
<div class="clear"> </div>
<label for="imagen">Subir imagen:</label>
<input type="file" name="imagen" id="imagen" />
<div class="clear"> </div>
<input type="submit" class="enviar" name="enviar" id="enviar" value="subir producto" />
</fieldset>
</form>
</div>
<script src="../js/jquery.js"></script>
<script src="../js/jquery.validate.js"></script>
<script src="../js/additional-methods.js"></script>
<script src="../js/messages_es.js"></script>
<script>
$("#form1").validate({
rules: {
nombreProducto: {
required: true
},
descripcion: {
required: true
},
precio: {
required: true,
number: true
},
imagen: {
required: true,
extension: "png|jpe?g|gif"
},
},
submitHandler: function(form) {
form.submit();
//alert("producto enviado");
}
});
</script>
<?php
if ( ! empty( $_POST ) ) {
include("config.php");
# Comprovamos que se haya subido un fichero
if (is_uploaded_file($_FILES["imagen"]["tmp_name"]))
{
# Cogemos la anchura y altura de la imagen
$info=getimagesize($_FILES["imagen"]["tmp_name"]);
//echo "<BR>".$info[0]; //anchura
//echo "<BR>".$info[1]; //altura
$imagenBinaria = addslashes(file_get_contents($_FILES['imagen']['tmp_name']));
mysqli_query($obj_conexion," INSERT INTO producto VALUES(null,'".$_POST["nombreProducto"]."','".$_POST["descripcion"]."',".$_POST["precio"].",".$info[0].",".$info[1].",'".$_FILES["imagen"]["type"]."','".$imagenBinaria."') ");
mysqli_close($obj_conexion);
}
}
?>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>
<title>product form</title>
<link rel="stylesheet" type="text/css" href="../css/style.css" />
</head>
<body>
<a href="index.php">Agregar Producto</a>
<div class="contenido">
<h1>Product Form</h1>
<form id="form1" action="producto.php" method="post" novalidate enctype="multipart/form-data">
<fieldset>
<legend>Buscar producto</legend>
<label for="nombreProducto">Buscar:</label>
<input type="text" name="producto" id="producto" size="70">
<input type="submit" class="buscar" name="buscar" id="buscar" value="buscar"/>
</fieldset>
</form>
</div>
<div class="paging"></div>
<?php
if ( ! empty( $_POST ) ) {
include("config.php");
$results = $obj_conexion->query("SELECT * FROM producto WHERE nombreProducto LIKE '%".$_POST["producto"]."%'");
while($row = $results->fetch_array()){
?>
<div class="element">
<hr>
<table>
<tr>
<td>
<img src="data:<?php echo $row['tipoImagen']; ?>;base64,<?php echo base64_encode($row['imagen']); ?>" height="160" width="213" /><br>
</td>
<td>
ID Producto: <?php echo $row['idproducto']; ?><br>
Producto: <?php echo $row['nombreProducto']; ?><br>
Descripción: <?php echo $row['descripcion']; ?><br>
Precio: $<?php echo $row['precio']; ?><br>
</td>
</tr>
</table>
<hr>
</div>
<?php
}
}
?>
<div class="paging"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="../js/jquery.ba-hashchange.js"></script>
<script src="../js/jquery.paging.min.js"></script>
<script>
/*
* Slicing the content with two pagers and using the URL Hash event
*/
(function() {
var prev = {
start: 0,
stop: 0
};
var content = $('.element');
var Paging = $(".paging").paging(content.length, {
onSelect: function() {
var data = this.slice;
content.slice(prev[0], prev[1]).css('display', 'none');
content.slice(data[0], data[1]).fadeIn("slow");
prev = data;
return true; // locate!
},
onFormat: function(type) {
switch (type) {
case 'block':
if (!this.active)
return '<span class="disabled">' + this.value + '</span>';
else if (this.value != this.page)
return '<em><a href="#' + this.value + '">' + this.value + '</a></em>';
return '<span class="current">' + this.value + '</span>';
case 'right':
case 'left':
if (!this.active) {
return '';
}
return '<a href="#' + this.value + '">' + this.value + '</a>';
case 'next':
if (this.active) {
return '<a href="#' + this.value + '" class="next">Next »</a>';
}
return '<span class="disabled">Next »</span>';
case 'prev':
if (this.active) {
return '<a href="#' + this.value + '" class="prev">« Previous</a>';
}
return '<span class="disabled">« Previous</span>';
case 'first':
if (this.active) {
return '<a href="#' + this.value + '" class="first">|<</a>';
}
return '<span class="disabled">|<</span>';
case 'last':
if (this.active) {
return '<a href="#' + this.value + '" class="prev">>|</a>';
}
return '<span class="disabled">>|</span>';
case 'fill':
if (this.active) {
return "...";
}
}
return ""; // return nothing for missing branches
},
format: '[< ncnnn! >]',
perpage: 3,
lapping: 0,
page: null // we await hashchange() event
});
$(window).hashchange(function() {
if (window.location.hash)
Paging.setPage(window.location.hash.substr(1));
else
Paging.setPage(1); // we dropped "page" support and need to run it by hand
});
$(window).hashchange();
})();
</script>
</body>
</html>


