Ver Mensaje Individual
  #1 (permalink)  
Antiguo 02/08/2010, 22:31
nachoz
 
Fecha de Ingreso: octubre-2007
Mensajes: 38
Antigüedad: 16 años, 5 meses
Puntos: 0
ayuda con saltos de linea <br> en php y mysql

Hola gente,

Estoy siguiendo un script para subir distintos archivos y queden almacenados en una BD y luego listarlos para su descarga.

El tema es que agregue la opción de listar también la descripción del archivo, pero estos salen lineales y no muestran los saltos de linea. Por ahí me dijieron que se utiliza el nl2br, pero como esta diseñado el script me complica.

La BD
Código SQL:
Ver original
  1. CREATE TABLE tbl_documentos (
  2.   id_documento INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  3.   titulo VARCHAR(50) NULL,
  4.   descripcion MEDIUMTEXT NULL,
  5.   contenido LONGBLOB NULL,
  6.   tamanio INTEGER UNSIGNED NULL,
  7.   tipo VARCHAR(50) NULL,
  8.   nombre_archivo VARCHAR(55) NULL,
  9.   tamanio_unidad VARCHAR(50) NULL,
  10.   PRIMARY KEY(id_documento)
  11. );

form.html
Código PHP:
Ver original
  1. <form id="test_upload" name="test_upload" action="upload.php" enctype="multipart/form-data" method="post">
  2.     <table border="0" cellpadding="0" cellspacing="0">
  3.         <tr>
  4.             <td>
  5.                 Titulo
  6.             </td>
  7.             <td>
  8.                 <input type="text" id="titulo" name="titulo"/>
  9.             </td>
  10.         </tr>
  11.         <tr>
  12.             <td colspan="2">
  13.                 Descripcion
  14.             </td>
  15.         </tr>
  16.         <tr>
  17.             <td colspan="2">
  18.                 <textarea id="descripcion" name="descripcion" cols="50" rows="5"></textarea>
  19.             </td>
  20.         </tr>
  21.         <tr>
  22.             <td colspan="2">
  23.                 Archivo <input type="file" id="archivo" name="archivo"/>
  24.             </td>
  25.         </tr>
  26.         <tr>
  27.             <td colspan="2">
  28.                 <input type="submit" value="Registrar Documento"/>
  29.             </td>
  30.         </tr>
  31.     </table>
  32. </form>

upload.php
Código PHP:
Ver original
  1. <?php
  2. //ESTA FUNCION LA USAREMOS PARA OBTENER EL TAMAÑO DE NUESTRO ARCHIVO
  3. function filesize_format($bytes, $format = '', $force = ''){
  4.     $bytes=(float)$bytes;
  5.     if ($bytes <1024){
  6.         $numero=number_format($bytes, 0, '.', ',');
  7.         return array($numero,"B");
  8.     }
  9.     if ($bytes <1048576){
  10.         $numero=number_format($bytes/1024, 2, '.', ',');
  11.         return array($numero,"KBs");
  12.     }
  13.     if ($bytes>= 1048576){
  14.         $numero=number_format($bytes/1048576, 2, '.', ',');
  15.         return array($numero,"MB");
  16.     }
  17. }
  18. //VERIFICAMOS QUE SE SELECCIONO ALGUN ARCHIVO
  19. if(sizeof($_FILES)==0){
  20.     echo "No se puede subir el archivo";
  21.     exit();
  22. }
  23. // EN ESTA VARIABLE ALMACENAMOS EL NOMBRE TEMPORAL QU SE LE ASIGNO ESTE NOMBRE ES GENERADO POR EL SERVIDOR
  24. // ASI QUE SI NUESTRO ARCHIVO SE LLAMA foto.jpg el tmp_name no sera foto.jpg sino un nombre como SI12349712983.tmp por decir un ejemplo
  25. $archivo = $_FILES["archivo"]["tmp_name"];
  26. //Definimos un array para almacenar el tamaño del archivo
  27. $tamanio=array();
  28. //OBTENEMOS EL TAMAÑO DEL ARCHIVO
  29. $tamanio = $_FILES["archivo"]["size"];
  30. //OBTENEMOS EL TIPO MIME DEL ARCHIVO
  31. $tipo = $_FILES["archivo"]["type"];
  32. //OBTENEMOS EL NOMBRE REAL DEL ARCHIVO AQUI SI SERIA foto.jpg
  33. $nombre_archivo = $_FILES["archivo"]["name"];
  34. //PARA HACERNOS LA VIDA MAS FACIL EXTRAEMOS LOS DATOS DEL REQUEST
  35. extract($_REQUEST);
  36. //VERIFICAMOS DE NUEVO QUE SE SELECCIONO ALGUN ARCHIVO
  37. if ( $archivo != "none" ){
  38.     //ABRIMOS EL ARCHIVO EN MODO SOLO LECTURA
  39.     // VERIFICAMOS EL TAÑANO DEL ARCHIVO
  40.     $fp = fopen($archivo, "rb");
  41.     //LEEMOS EL CONTENIDO DEL ARCHIVO
  42.     $contenido = fread($fp, $tamanio);
  43.     //CON LA FUNCION addslashes AGREGAMOS UN \ A CADA COMILLA SIMPLE ' PORQUE DE OTRA MANERA
  44.     //NOS MARCARIA ERROR A LA HORA DE REALIZAR EL INSERT EN NUESTRA TABLA
  45.     $contenido = addslashes($contenido);
  46.     //CERRAMOS EL ARCHIVO
  47.     fclose($fp);
  48.     // VERIFICAMOS EL TAÑANO DEL ARCHIVO
  49.     if ($tamanio <1048576){
  50.         //HACEMOS LA CONVERSION PARA PODER GUARDAR SI EL TAMAÑO ESTA EN b ó MB
  51.         $tamanio=filesize_format($tamanio);
  52.     }
  53.    
  54.     //CREAMOS NUESTRO INSERT
  55.     $qry = "INSERT INTO tbl_documentos ( titulo,nombre_archivo, descripcion, contenido, tamanio,tamanio_unidad, tipo ) VALUES
  56.     ('$titulo','$nombre_archivo', '$descripcion','$contenido','{$tamanio[0]}','{$tamanio[1]}', '$tipo')";
  57.    
  58.     //NOS CONECAMOS A LA BASE DE DATOS
  59.     //REMPLAZEN SUS VALOS POR LOS MIOS
  60.     mysql_connect("localhost","root","") or die("No se pudo conectar a la base de datos");
  61.    
  62.     //SELECCIONAMOS LA BASE DE DATOS CON LA CUAL VAMOS A TRABAJAR CAMBIEN EL VALOR POR LA SUYA
  63.     mysql_select_db("noticias");
  64.    
  65.     //EJECUTAMOS LA CONSULTA
  66.     mysql_query($qry) or die("Query: $qry <br />Error: ".mysql_error());
  67.    
  68.     //CERRAMOS LA CONEXION
  69.     mysql_close();
  70.     //NOTIFICAMOS AL USUARIO QUE EL ARCHVO SE HA ENVIADO O REDIRIGIMOS A OTRO LADO ETC.
  71.     echo "Archivo Agregado Correctamente<br>";
  72.     echo '<a href="form.html">Subir Otro Archivo</a><br > ';
  73. }else{
  74.     echo "No fue posible subir el archivo";
  75.     echo '<a href="form.html">Subir Otro Archivo</a><br > ';
  76. }
  77. ?>

getfile.php
Código PHP:
Ver original
  1. <?php
  2. //NOS CONECAMOS A LA BASE DE DATOS
  3. //REMPLAZEN SUS VALOS POR LOS MIOS
  4. mysql_connect("localhost","root","") or die("No se pudo conectar a la base de datos");
  5.  
  6. //SELECCIONAMOS LA BASE DE DATOS CON LA CUAL VAMOS A TRABAJAR CAMBIEN EL VALOR POR LA SUYA
  7. mysql_select_db("noticias");
  8.  
  9. //CONSTRUIMOS LA CONSULTA PARA OBTENER EL DOCUMENTO
  10. $qry="Select * from tbl_documentos where id_documento={$_REQUEST['id_documento']}";
  11. $res=mysql_query($qry) or die(mysql_error()." qry::$qry");
  12. $obj=mysql_fetch_object($res);     
  13.  
  14.  
  15. //OBTENEMOS EL TIPO MIME DEL ARCHIVO ASI EL NAVEGADOR SABRA DE QUE SE TRATA
  16. header("Content-type: {$obj->tipo}");
  17.  
  18. //OBTENEMOS EL NOMBRE DEL ARCHIVO POR SI LO QUE SE REQUIERE ES DESCARGARLO
  19. header('Content-Disposition: attachment; filename="'.$obj->nombre_archivo.'"');
  20.  
  21. //Y PO ULTIMO SIMPLEMENTE IMPRIMIMOS EL CONTENIDO DEL ARCHIVO
  22. print $obj->contenido;
  23.  
  24. //CERRAMOS LA CONEXION
  25. ?>

list.php
Código PHP:
Ver original
  1. <?php
  2. //NOS CONECAMOS A LA BASE DE DATOS
  3. //REMPLAZEN SUS VALOS POR LOS MIOS
  4. mysql_connect("localhost","root","") or die("No se pudo conectar a la base de datos");
  5.  
  6. //SELECCIONAMOS LA BASE DE DATOS CON LA CUAL VAMOS A TRABAJAR CAMBIEN EL VALOR POR LA SUYA
  7. mysql_select_db("noticias");
  8.  
  9. //CONSTRUIMOS EL QUERY PARA OBTENER LOS ARCHIVOS
  10. $qry="select
  11.         docs.*,
  12.         CASE docs.tipo
  13.             WHEN 'image/png' then
  14.                 'image'
  15.             WHEN 'image/jpg' then
  16.                 'image'
  17.             WHEN 'image/gif' then
  18.                 'image'
  19.             WHEN 'image/jpeg' then
  20.                 'image'
  21.             ELSE
  22.                 'file'
  23.         END as display
  24.     from tbl_documentos AS docs";
  25.  
  26. $prueba="select descripcion from tbl_documentos";
  27.  
  28. //EJECUTAMOS LA CONSULTA
  29. $res=mysql_query($qry) or die("Query: $qry ".mysql_error());
  30.  
  31.  
  32. //RECORREMOS LA CONSULTA
  33. while ($obj=mysql_fetch_object($res)) {
  34.     //SI EL TIPO DE DOCUMENTO ES UMAGEN LA MOSTRAMOS SI NO SOLO HACEMOS EL LINK
  35.     switch ($obj->display){
  36.         case "image":
  37.             echo "<div>
  38.                     <a href='getfile.php?id_documento={$obj->id_documento}'>
  39.                         <img src='getfile.php?id_documento={$obj->id_documento}' alt='$obj->titulo' />
  40.                     </a>
  41.                 </div><hr />";
  42.             break;
  43.         case "file":
  44.             echo "<div>
  45.                     <a href='getfile.php?id_documento={$obj->id_documento}'>$obj->titulo</a>
  46.                         <br>$obj->descripcion<br>
  47.                 </div><hr />";
  48.             break;         
  49.     }
  50.    
  51. }
  52.  
  53. //CERRAMOS LA CONEXION
  54. ?>

En esta ultima $obj->descripcion fue la única forma de poder llamar la descripcion de los archivos subidos.

Ojala y me ayuden se los agradeceria mucho :D