<?php
//conexion a la base de datos
$link = mysql_connect('localhost', 'root', '');
if (!$link)
die('Error al conectarse con MySQL: ' . mysql_error().' <br>Número del error: '.mysql_errno());
if (! @mysql_select_db("bd_laboratorio",$link)){
echo "No se pudo conectar correctamente con la Base de datos";
exit();
}
//le dimos click al boton grabar?
if (isset($_POST['guardar']))
{
$nombre = $_FILES['imagen']['name'];
$imagen_temporal = $_FILES['imagen']['tmp_name'];
$type = $_FILES['imagen']['type'];
//archivo temporal en binario
$itmp = fopen($imagen_temporal, 'r+b');
$imagen = fread($itmp, filesize($imagen_temporal));
fclose($itmp);
//escapando los caracteres
$imagen = mysql_real_escape_string($imagen);
$respuesta = mysql_query("insert into subir_imagen (id, nombre_imagen, imagen, tipo)
values(0, '$nombre', '$imagen', '$type')", $link);
//redireccionamos
header("Location: index.php?".($respuesta ? 'ok' : 'error'));
}
//guardado OK
if (isset($_GET['ok']))
{
echo '<p>Guardado Exitosamente</p>';
}
//si no se guardo de manera correcta?
if (isset($_GET['error']))
{
echo '<p>Ocurrio un error a la hora de realizar la insercion...</p>';
}
//formulario que nos permite subir a la BD el archivo
echo '
<form action="index.php" enctype="multipart/form-data" method="post">
<input type="file" name="imagen" id="imagen" />
<input type="submit" value="Guardar" name="guardar" />
</form>';
$sql = mysql_query("select id, nombre_imagen, imagen from subir_imagen", $link);
$imagenes = array();
while($row = mysql_fetch_assoc($sql))
{
$imagenes[$row['id']] = array(
'id' => (int) $row['id'],
'nombre' => $row['nombre_imagen'],
'imagen' => $row['imagen'],
);
}
//existen imagenes para mostrar?
if (!empty($imagenes))
{
echo '<span style="text-decoration:underline;">Imagenes guardadas en la BD:</span>';
foreach($imagenes as $valor)
echo '<p>', $valor['id'] ,' - ' , $valor['nombre'] ,' - <a href="ver.php?i=', $valor['id'] ,'">Ver Imagen</a></p>';
}
?>