Foros del Web » Programando para Internet » PHP »

seleccionar parte a mostrar...

Estas en el tema de seleccionar parte a mostrar... en el foro de PHP en Foros del Web. hola estoy haciendo un sistema de encuestas y me gustaria que cuando el usuario vote aparezcan los resultados, pero que a su vez se desaparezcan ...
  #1 (permalink)  
Antiguo 25/10/2003, 15:16
Avatar de cadrogui  
Fecha de Ingreso: junio-2003
Mensajes: 875
Antigüedad: 20 años, 10 meses
Puntos: 5
seleccionar parte a mostrar...

hola estoy haciendo un sistema de encuestas y me gustaria que cuando el usuario vote aparezcan los resultados, pero que a su vez se desaparezcan las opciones de voto..

hice esto...


Código PHP:

<?
$conecta
=mysql_connect("localhost","cadrogui","mikel") or die ("Error al conectar a la Bd");
mysql_select_db("revista",$conecta);
$verificamos=mysql_query("select * from encuesta",$conecta);

?>
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form name="form1" method="post" action="<? $PHP_SELF ?>">
  <table width="509" border="0" cellpadding="0" cellspacing="0">
    <!--DWLayoutDefaultTable-->
    <tr> 
      <td width="275" height="147">&nbsp;</td>
      <td width="207">&nbsp;</td>
      <td width="27">&nbsp;</td>
    </tr>
    <tr> 
      <td height="234">&nbsp;</td>
      <td valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
          <!--DWLayoutTable-->
          <tr> 
            <td height="25" colspan="2" valign="top">pregunta</td>
          </tr>
          <tr> 
            <td width="169" height="31" valign="top">resp 1</td>
            <td width="38" valign="top"><input name="voto" type="radio" value="1"></td>
          </tr>
          <tr> 
            <td height="36" valign="top">resp 2</td>
            <td valign="top"><input name="voto" type="radio" value="2"></td>
          </tr>
          <tr> 
            <td height="50" valign="top">resp 3</td>
            <td valign="top"><input name="voto" type="radio" value="3"></td>
          </tr>
          <tr> 
            <td height="50" valign="top">resp 4</td>
            <td valign="top"><input name="voto" type="radio" value="4"></td>
          </tr>
          <tr> 
            <?
if ($Submit){

$voto $_POST["voto"];
echo 
"voto realizado"'<br>';
$conexion=mysql_connect("localhost","cadrogui","mikel");
mysql_select_db("revista",$conexion);
//$voto manda el valor del boton que ha sido pulsado y se asigna a p
$consulta=mysql_query ("update encuesta set p$voto = p$voto+1");

mysql_select_db("revista",$conexion);
$con=mysql_query("select * from encuesta");
$img=mysql_fetch_array($con);
$numero =  $img["p1"];
print (
'<img src="barra1.gif" width="'.$numero.'" height="12">');
}
?>
            <td height="42" valign="top">votar 
              <input type="submit" name="Submit" value="Enviar"> </td>
            <td valign="top"><!--DWLayoutEmptyCell-->&nbsp;</td>
          </tr>
        </table></td>
      <td>&nbsp;</td>
    </tr>
    <tr> 
      <td height="24">&nbsp;</td>
      <td valign="top"></td>
      <td>&nbsp;</td>
    </tr>
    <tr> 
      <td height="30">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
</form>
</body>
</html>
espero se entienda..


salu2
__________________
La mejor manera de aprender es por medio de un aprendizaje significativo....

http://www.cocert.cl
  #2 (permalink)  
Antiguo 25/10/2003, 16:00
Avatar de Manoloweb  
Fecha de Ingreso: enero-2002
Ubicación: Monterrey
Mensajes: 2.454
Antigüedad: 22 años, 3 meses
Puntos: 5
Y que pasará cuando el usuario vaya a otra pagina y luego regrese? le volverá a salir la opción de votar?

Por que no usas algun metodo para "recordar" quien ha votado? Puede ser a través de tu mismo sistema de usuarios, usando cookies o alguna combinación de ambas cosas...

__________________
Manoloweb
  #3 (permalink)  
Antiguo 25/10/2003, 16:03
Avatar de cadrogui  
Fecha de Ingreso: junio-2003
Mensajes: 875
Antigüedad: 20 años, 10 meses
Puntos: 5
buena pregunta pero la pregunra del millon es ¿como lo hago?
__________________
La mejor manera de aprender es por medio de un aprendizaje significativo....

http://www.cocert.cl
  #4 (permalink)  
Antiguo 25/10/2003, 16:14
Avatar de Manoloweb  
Fecha de Ingreso: enero-2002
Ubicación: Monterrey
Mensajes: 2.454
Antigüedad: 22 años, 3 meses
Puntos: 5
Lo mas simple que se me ocurre es guardar una cookie con el identificador de la encuesta.

Y si al entrar a la pagina de la encuesta detectas esa cookie, simplemente muestras los resultados.

Código PHP:
setcookie("Votada","1"); 
Y al entrar buscas la cookie:

Código PHP:
if ($_COOKIE["Votada"]==1) {
//muestras resultados
} else {
//muestras formulario


Algo así...

Te dejo este link: http://mx.php.net/manual/es/features.cookies.php
__________________
Manoloweb
  #5 (permalink)  
Antiguo 25/10/2003, 16:17
Avatar de cadrogui  
Fecha de Ingreso: junio-2003
Mensajes: 875
Antigüedad: 20 años, 10 meses
Puntos: 5
buenisima, entonces tanto el fromulario como los resultados deben estar en la instrucciones del if()...


corrijanme si estoy ekivocado

salu2
__________________
La mejor manera de aprender es por medio de un aprendizaje significativo....

http://www.cocert.cl
  #6 (permalink)  
Antiguo 25/10/2003, 16:52
Avatar de cadrogui  
Fecha de Ingreso: junio-2003
Mensajes: 875
Antigüedad: 20 años, 10 meses
Puntos: 5
intente lo de la cookie, la puse asi:

if($Submit){
setcookie("Votada","1",time()+3600);
y todo lo demas




pero ahora no se donde poner el resto del code
__________________
La mejor manera de aprender es por medio de un aprendizaje significativo....

http://www.cocert.cl
  #7 (permalink)  
Antiguo 25/10/2003, 17:04
Avatar de cadrogui  
Fecha de Ingreso: junio-2003
Mensajes: 875
Antigüedad: 20 años, 10 meses
Puntos: 5
lo deje asi pero no funciona me da errores la cookie y no me muestra los resultados....


Código PHP:

<?
if ($Submit){
setcookie("Votada","1");
$voto $_POST["voto"];
echo 
"voto realizado"'<br>';
$conexion=mysql_connect("localhost","cadrogui","mikel");
mysql_select_db("revista",$conexion);
//$voto manda el valor del boton que ha sido pulsado y se asigna a p
$consulta=mysql_query ("update encuesta set p$voto = p$voto+1");

}
if (
$_COOKIE["Votada"]==1) {

mysql_select_db("revista",$conexion);
$con=mysql_query("select * from encuesta");
$img=mysql_fetch_array($con);

$numero =  $img["p1"];
$numero2 $img["p2"];
$numero3 $img["p3"];
$numero4 $img["p4"];

print (
'<img src="img/barra1.gif" width="'.$numero.'" height="9">').'<br>';
print (
'<img src="img/barra2.gif" width="'.$numero2.'" height="9">').'<br>';
print (
'<img src="img/barra3.gif" width="'.$numero3.'" height="9">').'<br>';
print (
'<img src="img/barra4.gif" width="'.$numero4.'" height="9">').'<br>';
} else {
echo 
"aka va el form";
}


?>
me sale esto:

Warning: Cannot add header information - headers already sent by (output started at c:\appserv\www\revista\encu.php:14) in c:\appserv\www\revista\encu.php on line 48
voto realizado
aka va el form

la linea 48:

setcookie("Votada","1");

y no se ke hacer...


salu2
__________________
La mejor manera de aprender es por medio de un aprendizaje significativo....

http://www.cocert.cl
  #8 (permalink)  
Antiguo 25/10/2003, 18:19
Avatar de jpinedo
Colaborador
 
Fecha de Ingreso: septiembre-2003
Ubicación: Lima, Perú
Mensajes: 3.120
Antigüedad: 20 años, 7 meses
Puntos: 41
Recuerda que "setcookie()" tiene que estar antes de escribir cualquier cosa en la página. Nada de HTML ni ningún "echo".

Al parecer se está escribiendo algo en la línea 14. Puedes postear qué hay en esa línea?

Saludos
  #9 (permalink)  
Antiguo 25/10/2003, 18:27
Avatar de cadrogui  
Fecha de Ingreso: junio-2003
Mensajes: 875
Antigüedad: 20 años, 10 meses
Puntos: 5
este es el code completo:

Código PHP:

<?
$conecta
=mysql_connect("localhost","cadrogui","mikel") or die ("Error al conectar a la Bd");
mysql_select_db("revista",$conecta);
$verificamos=mysql_query("select * from encuesta",$conecta);

?>
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form name="form1" method="post" action="<? $PHP_SELF ?>">
  <table width="509" border="0" cellpadding="0" cellspacing="0">
    <!--DWLayoutDefaultTable-->
    <tr> 
      <td width="275" height="147">&nbsp;</td>
      <td width="207">&nbsp;</td>
      <td width="27">&nbsp;</td>
    </tr>
    <tr> 
      <td height="234">&nbsp;</td>
      <td valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
          <!--DWLayoutTable-->
          <tr> 
            <td height="25" colspan="2" valign="top">pregunta</td>
          </tr>
          <tr> 
            <td width="169" height="31" valign="top">resp 1</td>
            <td width="38" valign="top"><input name="voto" type="radio" value="1"></td>
          </tr>
          <tr> 
            <td height="36" valign="top">resp 2</td>
            <td valign="top"><input name="voto" type="radio" value="2"></td>
          </tr>
          <tr> 
            <td height="50" valign="top">resp 3</td>
            <td valign="top"><input name="voto" type="radio" value="3"></td>
          </tr>
          <tr> 
            <td height="50" valign="top">resp 4</td>
            <td valign="top"><input name="voto" type="radio" value="4"></td>
          </tr>
          <tr> 
            <?
if ($Submit){
setcookie("Votada","1");
$voto $_POST["voto"];
echo 
"voto realizado"'<br>';
$conexion=mysql_connect("localhost","cadrogui","mikel");
mysql_select_db("revista",$conexion);
//$voto manda el valor del boton que ha sido pulsado y se asigna a p
$consulta=mysql_query ("update encuesta set p$voto = p$voto+1");

mysql_select_db("revista",$conexion);
$con=mysql_query("select * from encuesta");
$img=mysql_fetch_array($con);

$numero =  $img["p1"];
$numero2 $img["p2"];
$numero3 $img["p3"];
$numero4 $img["p4"];

print (
'<img src="img/barra1.gif" width="'.$numero.'" height="9">').'<br>';
print (
'<img src="img/barra2.gif" width="'.$numero2.'" height="9">').'<br>';
print (
'<img src="img/barra3.gif" width="'.$numero3.'" height="9">').'<br>';
print (
'<img src="img/barra4.gif" width="'.$numero4.'" height="9">').'<br>';
}

?>
            <td height="42" valign="top">votar 
              <input type="submit" name="Submit" value="Enviar"> </td>
            <td valign="top"><!--DWLayoutEmptyCell-->&nbsp;</td>
          </tr>
        </table></td>
      <td>&nbsp;</td>
    </tr>
    <tr> 
      <td height="24">&nbsp;</td>
      <td valign="top"></td>
      <td>&nbsp;</td>
    </tr>
    <tr> 
      <td height="30">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
</form>
</body>
</html>
sace lo del if con la cookie pq me dio puos problemas, ayudenme a organizar el code....por fa


salu2

pd: este code hace que aparezcan las barras de los votos pero el form sigue ahi....quiero sacarloooooooooooooooooo!!!!!!!!!!!!



ahh la linea 14 es la del tag form
__________________
La mejor manera de aprender es por medio de un aprendizaje significativo....

http://www.cocert.cl
  #10 (permalink)  
Antiguo 25/10/2003, 21:37
Avatar de jpinedo
Colaborador
 
Fecha de Ingreso: septiembre-2003
Ubicación: Lima, Perú
Mensajes: 3.120
Antigüedad: 20 años, 7 meses
Puntos: 41
Ajá...!

Bueno... ese es justamente el problema... que ya has mandado código HTML antes del setcookie()...

Lo que deberías hacer es algo así:
Código PHP:
if ($submit){
//define la cookie a 1
//script que actualiza tu base de datos ...UPDATE...;
}else{
    if (
$_COOKIE['nombre']==1){
        
//mostrar resultados;
    
}else{
        
//mostrar formulario;
    
}
}

Saludos
  #11 (permalink)  
Antiguo 26/10/2003, 09:03
Avatar de cadrogui  
Fecha de Ingreso: junio-2003
Mensajes: 875
Antigüedad: 20 años, 10 meses
Puntos: 5
gracias, mira el code quedo asi:

Código PHP:

<?
if ($submit){
setcookie("Votada","1");
$voto $_POST["voto"];
echo 
"voto realizado"'<br>';
$conexion=mysql_connect("localhost","cadrogui","mikel");
mysql_select_db("revista",$conexion);
//$voto manda el valor del boton que ha sido pulsado y se asigna a p
$consulta=mysql_query ("update encuesta set p$voto = p$voto+1");

}else{

    if (
$_COOKIE['votada']==1){
        
mysql_select_db("revista",$conexion);
$con=mysql_query("select * from encuesta");
$img=mysql_fetch_array($con);

$numero =  $img["p1"];
$numero2 $img["p2"];
$numero3 $img["p3"];
$numero4 $img["p4"];

print (
'<img src="img/barra1.gif" width="'.$numero.'" height="9">').'<br>';
print (
'<img src="img/barra2.gif" width="'.$numero2.'" height="9">').'<br>';
print (
'<img src="img/barra3.gif" width="'.$numero3.'" height="9">').'<br>';
print (
'<img src="img/barra4.gif" width="'.$numero4.'" height="9">').'<br>';

    }else{

<
form name="form1" method="post" action="<? $PHP_SELF ?>">
  <
table width="509" border="0" cellpadding="0" cellspacing="0">
    <!--
DWLayoutDefaultTable-->
    <
tr
      <
td width="275" height="147">&nbsp;</td>
      <
td width="207">&nbsp;</td>
      <
td width="27">&nbsp;</td>
    </
tr>
    <
tr
      <
td height="234">&nbsp;</td>
      <
td valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
          <!--
DWLayoutTable-->
          <
tr
            <
td height="25" colspan="2" valign="top">pregunta</td>
          </
tr>
          <
tr
            <
td width="169" height="31" valign="top">resp 1</td>
            <
td width="38" valign="top"><input name="voto" type="radio" value="1"></td>
          </
tr>
          <
tr
            <
td height="36" valign="top">resp 2</td>
            <
td valign="top"><input name="voto" type="radio" value="2"></td>
          </
tr>
          <
tr
            <
td height="50" valign="top">resp 3</td>
            <
td valign="top"><input name="voto" type="radio" value="3"></td>
          </
tr>
          <
tr
            <
td height="50" valign="top">resp 4</td>
            <
td valign="top"><input name="voto" type="radio" value="4"></td>
          </
tr>
          <
tr
            
            <
td height="42" valign="top">votar 
              
<input type="submit" name="Submit" value="Enviar"> </td>
            <
td valign="top"><!--DWLayoutEmptyCell-->&nbsp;</td>
          </
tr>
        </
table></td>
      <
td>&nbsp;</td>
    </
tr>
    <
tr
      <
td height="24">&nbsp;</td>
      <
td valign="top"></td>
      <
td>&nbsp;</td>
    </
tr>
    <
tr
      <
td height="30">&nbsp;</td>
      <
td>&nbsp;</td>
      <
td>&nbsp;</td>
    </
tr>
  </
table>
</
form>

    }
}
}
?>

y me sda el sgte error:

Parse error: parse error, unexpected '<' in c:\appserv\www\revista\encu2.php on line 30

la linea 30 es la sgte:

<form name="form1" method="post" action="<? $PHP_SELF ?>">

que puede ser??



salu2
__________________
La mejor manera de aprender es por medio de un aprendizaje significativo....

http://www.cocert.cl
  #12 (permalink)  
Antiguo 26/10/2003, 09:39
Avatar de cadrogui  
Fecha de Ingreso: junio-2003
Mensajes: 875
Antigüedad: 20 años, 10 meses
Puntos: 5
en realidad el error esta dado por cualquier codigo html que es puesto en esa seccion, como puedo insertar el code html?....


salu2
__________________
La mejor manera de aprender es por medio de un aprendizaje significativo....

http://www.cocert.cl
  #13 (permalink)  
Antiguo 26/10/2003, 14:18
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
El concepto de cookies o de sesiones incluso es que al terminar tu proceso que insertas tus datos en tu BD o mandas un e-mail o lo que corresponda, "seteas" (setcookie) tus cookies y redireccionas a otra página o si misma para conseguir que tus cookies queden disponibles en tu $_COOKIE array superglobal.

El psudo código de cualquier aplicación debería ser así:

1) formulario pides datos
2) formulario envia datos a script_proceso.php o a si mismo.
3) script_proceso.php procesa esos datos: Valida datos si es necesario, intgresa datos en tu BD o manda un e-mail o hace cualquier otra operación.
4) termina la ejecución de tu script_proceso.php --> redireccionas a OTRO script o a si mismo para mostrar mensajes de error/exito del proceso. Para saber que error tuvistes o bien que mensaje de "exito" mostrar, puedes usar una variable de control tipo:

script_proceso.php
Código PHP:
<?
// recoges tus variables del formulario y las procesas ..

// termina el proceso .. Tu proceso genera alguna variable con un código del estado del proceso (exito o error). Y redireccionas automáticamente.

header("Location: otro_sitio_o_esta_misma_pagina.php?codigo=$codigo");
?>
Si necesitas usar cookies, antes de tu header() debes de hacer tu setcookie() correspondiente .. De esta forma, en esta sección del código NO debe de existir nada de HTML. Si te dás cuenta, para evitar ese "HTML" lo que se hace es "redireccionar" a otra página que será la que muestre el mensaje deacuerdo al valor que tome la varible $_GET['codigo'] ...

De esta forma, también evitas el típico problema que sucede cuando RECARGAS esa página que haces un proceso y muestras el mensajito de "voto realizado" .. Si recargo página voy a producir registros duplicados en tu BD (el código se ejecuta una vez más. Se pide confirmación de volver a enviar los datos del navegador .. si doy al "OK" .. se producirá este efecto).

Todo pasa por saber estructurar tu código y sobre todo pensar que hace PHP .. PHP procesa la página en el servidor y de tu lógica usada (estructuras de control .. bucles .. etc) generaras un HTML/javascirpt/etc u otro.

Si lo piensas así .. para "PHP" no le hace falta tu HTML cuando está realizando un proceso tipo "insertar un dato en tu BD".

Un saludo,

PD: puedes solventar estos problemas de cabeceras usando ob_start() y demás funciones de control del Buffer de salida de PHP. Pero, si te acostumbras a estructurar tu código sería lo ideal.
__________________
Por motivos personales ya no puedo estar con Uds. Fue grato haber compartido todos estos años. Igualmente los seguiré leyendo.
  #14 (permalink)  
Antiguo 26/10/2003, 20:30
Avatar de jpinedo
Colaborador
 
Fecha de Ingreso: septiembre-2003
Ubicación: Lima, Perú
Mensajes: 3.120
Antigüedad: 20 años, 7 meses
Puntos: 41
Mira bien...

Ese "pase error" que te sale es porque no estás especificando salida del HTML. Podrías utilizar por ejemplo un "echo" así:
Código PHP:
}else{
echo 
"<form name=\"form1\" method=\"post\" action=\"".$PHP_SELF."\">
  <table width=\"509\" border..." 
//etc, etc... 
Recuerda que si utilizas "echo" debes poner contrabarras...

Saludos
  #15 (permalink)  
Antiguo 26/10/2003, 20:55
Avatar de cadrogui  
Fecha de Ingreso: junio-2003
Mensajes: 875
Antigüedad: 20 años, 10 meses
Puntos: 5
gracias a to2 por su ayuda..


salu2
__________________
La mejor manera de aprender es por medio de un aprendizaje significativo....

http://www.cocert.cl
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 12:53.