Ver Mensaje Individual
  #7 (permalink)  
Antiguo 20/06/2011, 16:15
cabritillo77
 
Fecha de Ingreso: mayo-2011
Mensajes: 33
Antigüedad: 12 años, 11 meses
Puntos: 4
Respuesta: problema con imagen en un echo

Yo lo que hice fue con phpMyAdmin entre a la tabla y el campo foto le puse como valor default logoclub.jpg una imagen que posteriormente guarde en la carpeta donde suben todas las que llegan por el formulario. De tal manera que si subo una noticia sin imagen esa linea de la base de datos tendra titulo, texto pero no tendra foto insertada y automaticamente se le asignara el valor default que yo le puse.
Te paso el script de insertar las noticias y el de listar noticias:

Como soy muy novato utilizo 2 script para insertar noticia, uno cuando quiero subir imagenes y otro cuando la noticia va sin imagenes:

add-noticia.php
Código PHP:
<?php
session_start
();

if(!empty(
$_SESSION['username'])){ 

echo 
'Bienvenido '.$_SESSION['username']; 
 }else{ 
echo 
'No estas logueado<br>'
echo 
'Esta pagina es restringida!'
session_unset('username');
session_unset('password');
session_destroy(); // Todas. 
echo "<meta http-equiv='Refresh' content='0; URL=index.php'/>";

}
// incluimos el archivo de conexion
include ('db-cnx.php');

// recibimos el formulario
if(isset($_POST['enviar']) && $_POST['enviar'] == 'Enviar'){
// comprobamos que el formulario no envie campos vacios
if(!empty($_POST['notTitulo']) && $_POST['notTexto'] &&
$_POST['notCategoriaID']){
// creamos las variables y les asignamos los valores a insertar
$notTitulo $_POST['notTitulo'];
$notTexto $_POST['notTexto'];
$notCategoriaID $_POST['notCategoriaID'];
$notTitulo strtoupper ($notTitulo);
$notTexto ucfirst ($notTexto);
$link $_POST['link'];
   
// hacemos el INSERT en la BD
$sqlInsertNot mysql_query("INSERT INTO sn_noticias
(notTitulo, notTexto, notCategoriaID, link)
VALUES ('$notTitulo', '$notTexto', '$notCategoriaID', '$link')"
,
$db_link) or die(mysql_error());
// enviamos un mensaje de exito
echo "Los datos fueron gurdados correctamente";
}else{
// si el formulario envia algun campo vacio
// enviamos un mensaje de error
echo "Debe llenar todos los campos del formulario";
}
}

?>
<!-- el formulario -->
<? 
if(!empty($_SESSION['username'])){ 

echo 
'Bienvenido:'.$_SESSION['username']; 
 }else{ 
echo 
'No estas logueado<br>'
echo 
'Esta pagina es restringida!'
}
?>
<div style="position: absolute; left: 300; top: 50; width: 300; height: 500">
<? echo "Bienvenido ".$_SESSION['username']."";?>
<form name="noticia" action="<?php $_SERVER['PHP_SELF']; ?>" method="post" enctype='multipart/form-data'>
<body bgcolor="#FFE821">

<p>
Título de la Noticia<br />
<input type="text" name="notTitulo" size="50" />
</p>
<p>
Texto de la Noticia<br />
<textarea name="notTexto" rows="10" cols="50"></textarea>
</p>

<p>
Categoría<br />
<select name="notCategoriaID">

<option value="">Escoger de la Lista</option>


<?php
// asignamos una categoria a la noticia
// mediante un select
$sqlQueryCat mysql_query("SELECT * FROM sn_categorias"$db_link)
or die(
mysql_error());
// creamos un bucle while
// que nos muestre todas las categorias
// que tenemos guardadas en la BD
while($rowCat mysql_fetch_array($sqlQueryCat)){
echo 
"<option value='$rowCat[cat_ID]'>$rowCat[catCategoria]</option>";
}
?>
</select>
</p>
<p>
Enlace:
<input type="text" name="link" size="60" />
<p>
<input type="submit" name="enviar" value="Enviar" />
</p>
</form>
<br><br>
<a href="indexr.php">Ver Noticias</a>
<br><br>
<a href="add.categoria.php">Añadir Nueva Categoria</a>

</div>
add-noticia-imagen.php

Código PHP:
<?php
session_start
();

if(!empty(
$_SESSION['username'])){ 

echo 
'Bienvenido '.$_SESSION['username']; 
 }else{ 
echo 
'No estas logueado<br>'
echo 
'Esta pagina es restringida!'
session_unset('username');
session_unset('password');
session_destroy(); // Todas. 
echo "<meta http-equiv='Refresh' content='0; URL=index.php'/>";

}
// incluimos el archivo de conexion
include ('db-cnx.php');
// recibimos el formulario
if(isset($_POST['enviar']) && $_POST['enviar'] == 'Enviar'){
// comprobamos que el formulario no envie campos vacios
if(!empty($_POST['notTitulo']) && $_POST['notTexto'] &&
$_POST['notCategoriaID']){
// creamos las variables y les asignamos los valores a insertar
$notTitulo $_POST['notTitulo'];
$notTexto $_POST['notTexto'];
$notCategoriaID $_POST['notCategoriaID'];
$notTitulo strtoupper ($notTitulo);
$notTexto ucfirst ($notTexto);
$nombre_archivo $_FILES["foto"]["name"];  
$tipo_archivo $_FILES["foto"]["type"];  
$tamano_archivo $_FILES["foto"]["size"];
$link $_POST['link'];
if (!((
strpos($tipo_archivo"gif") || strpos($tipo_archivo"jpeg")) && (    $tamano_archivo 1000000))) 
{  
    echo 
"La extensión o el tamaño de los archivos no es correcta. <br><br><table><tr><td><li>Se permiten archivos .gif o .jpg<br><li>se permiten archivos de 1Mg máximo.</td></tr></table>";
}
else 
{  
    
$nom_img$nombre_archivo
     
    
$directorio 'imagesr/';
    if (
move_uploaded_file($_FILES['foto']['tmp_name'],$directorio "/" $nom_img)) 
    {
    
  
// hacemos el INSERT en la BD
$sqlInsertNot mysql_query("INSERT INTO sn_noticias
(notTitulo, notTexto, notCategoriaID, foto)
VALUES ('$notTitulo', '$notTexto', '$notCategoriaID', '$nom_img')"
,
$db_link) or die(mysql_error());

// si el formulario envia algun campo vacio
// enviamos un mensaje de error
echo "                                                                                                               La noticia se publico correctamente";
}else{
    
echo 
"error al subir la foto";
}

}
}else{
echo 
"Debe introducir Titulo, Texto y Categoria de la Noticia";
}
}
?>
<!-- el formulario -->
<? 
if(!empty($_SESSION['username'])){ 

echo 
'Bienvenido:'.$_SESSION['username']; 
 }else{ 
echo 
'No estas logueado<br>'
echo 
'Esta pagina es restringida!'
}
?>
<div style="position: absolute; left: 300; top: 50; width: 300; height: 500">
<? echo "Bienvenido ".$_SESSION['username']."";?>
<form name="noticia" action="<?php $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"
>
<body bgcolor="#FFE821">
<p>
Título de la Noticia<br />
<input type="text" name="notTitulo" size="50" />
</p>
<p>
Texto de la Noticia<br />
<textarea name="notTexto" rows="10" cols="50"></textarea>
</p>
<p>
Inserta imagen <font color="#FE0404">(jpg o gif menos a 1Mg y sin acentos en el nombre del fichero)</font><br />
<input type="file" name="foto" size="50" />
<p>
Categoría<br />
<select name="notCategoriaID">

<option value="">Escoger de la Lista</option>


<?php
// asignamos una categoria a la noticia
// mediante un select
$sqlQueryCat mysql_query("SELECT * FROM sn_categorias"$db_link)
or die(
mysql_error());
// creamos un bucle while
// que nos muestre todas las categorias
// que tenemos guardadas en la BD
while($rowCat mysql_fetch_array($sqlQueryCat)){
echo 
"<option value='$rowCat[cat_ID]'>$rowCat[catCategoria]</option>";
}
?>
</select>
</p>
<p>
Enlace:
<input type="text" name="link" size="60" />
<p>
<p>
<input type="submit" name="enviar" value="Enviar" />
</p>
</form>
<br><br>
<a href="index.php">Ver Noticias</a>
<br><br>
<!--
<a href="add.categoria.php">Añadir Nueva Categoria</a>
-->
</div>
Y finalmente el script que muestra las noticias:

list-noticia.campeonatos-final.php

Código PHP:
<?

// verificamos si se ha enviado
// alguna variable via GET
if(isset($_GET['id']) && $_GET['categoria']){
    
// asignamos los valores
    // a las variables que usaremos
    
$cat_ID $_GET['id'];
    
$categoria $_GET['categoria'];
}
// armamos la consulta
$sqlQueryNot mysql_query("SELECT not_ID, notTitulo, notTexto, foto, link FROM sn_noticias where notCategoriaID='1' ORDER BY not_ID DESC LIMIT 4"$db_link) or die(mysql_error);
//Declarar el array 
$not_ID = array(not_ID);
$ArrayTitulo = array(notTitulo);
$ArrayTexto = array(notTexto); 
$Arrayfoto = array(foto); 
$Arraylink = array(link);   
  while(
$rowNot mysql_fetch_array($sqlQueryNot)){ 
$not_ID[]= $rowNot[not_ID];                     
$ArrayTitulo[]= $rowNot[notTitulo];
$ArrayTexto[]= $rowNot[notTexto];
$Arrayfoto[]= $rowNot[foto];
$Arraylink[]= $rowNot[link];
}
 
?>   
<body bgcolor="#FFE821">

<div style="position: absolute; left: 280; top: 230; width: 240; height: 1400; float:left">

<table border="0" cellpadding="0" cellspacing="0"  width="279"  bgcolor="#ffffff">

<? include("docs/esquinasarriba.txt");?>

<table class="fondoblanco" width="257">

<tr>

<td align="center"><font color="#ff7f00"><b><? echo $ArrayTitulo[1]; ?></b></font>

</td>
</tr>

<tr>
<td align="center">
<p>
<? echo $ArrayTexto[1]; ?>
<br><br>
</p>


<center>
<a href="imagesr/<? echo $Arrayfoto[1]; ?>"><img src="imagesr/<? echo $Arrayfoto[1]; ?>" width="85" height="85"></a><br><br>

<a href="<? echo $Arraylink[1]; ?>">VER ENLACE</a><br><br>



<hr>
</td>
</tr>

<!------------------------------------------------------------------------------------->

<tr>

<td align="center"><font color="#ff7f00"><b><? echo $ArrayTitulo[2]; ?></b></font>

</td>
</tr>

<tr>
<td align="center">
<p>
<? echo $ArrayTexto[2]; ?>
<br><br>
</p>


<center>
<a href="imagesr/<? echo $Arrayfoto[2]; ?>"><img src="imagesr/<? echo $Arrayfoto[2]; ?>" width="85" height="85"></a><br><br>

<a href="<? echo $Arraylink[2]; ?>">VER ENLACE</a><br><br>



<hr>
</td>
</tr>

<!------------------------------------------------------------------------------------->
</table>




<? include("docs/esquinasabajo.txt");?>

</table>
<br><br>
</div>
</body>
Espero haberte ayudado y no haberte liado.

Si no tengo imagen para la noticia uso el primer script y como imagen se muestra el logo de mi club y si tengo imagen uso el segundo script y me aparece la imagen.
Me imagino que se podra hacer un script solamente para todo esto pero como no tenia demasiado tiempo lo hice asi.