Foros del Web » Programando para Internet » PHP »

Necesito ayuda con varias cosas...

Estas en el tema de Necesito ayuda con varias cosas... en el foro de PHP en Foros del Web. que tal... despues de tanto luchar.. necesitaria un poco de ayuda... 1) necesito crear una tabla para la base de datos que se llame usrsorteo ...
  #1 (permalink)  
Antiguo 19/05/2006, 17:37
 
Fecha de Ingreso: diciembre-2005
Ubicación: Mar del Plata
Mensajes: 146
Antigüedad: 18 años, 3 meses
Puntos: 2
Necesito ayuda con varias cosas...

que tal... despues de tanto luchar.. necesitaria un poco de ayuda...

1)

necesito crear una tabla para la base de datos que se llame usrsorteo que recoja datos de nombre y de email:

CREATE TABLE `mp_usrsorteo` (
`id` int(11) NOT NULL auto_increment,
`email` varchar(255) NOT NULL default '',
`nombre` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


tengo esta y quisiera saber si esta bien.

2) necesito que a esa base de datos se le registren los datos que se vallan a poner aca:

{if $clicks_ganador}
<script language="javascript" type="text/javascript">
alert('The pixel you selected is a winner pixel!! Please click OK to enter the contest!!\n Just fill the form with your Name and Email');
var nombre = prompt("Please write your name:","Your Name");
var email = prompt("Please write your email:","[email protected]");
window.open('/reg.php');
alert('Your data has been registered!! Now you are in the contest.\nRemember that you can try all times you want!!');
window.location = 'reg.php';
</script>

si alguien me pudiera ayudar le agradeceria muchisimo... ya que es muy importante para mi..

Gracias de antemano!
  #2 (permalink)  
Antiguo 19/05/2006, 18:00
okram
Invitado
 
Mensajes: n/a
Puntos:
Para insertar datos en una BD debes usar sentencias php y no codigos javascript...

Una cosa que puedes hacer es esta:

Código PHP:
<?php
if(!isset($_GET['nombre']) || !isset($_GET['email'])) {
?>
    <script language="javascript" type="text/javascript">
alert('The pixel you selected is a winner pixel!! Please click OK to enter the contest!!\n Just fill the form with your Name and Email');
    var nombre = prompt("Please write your name:","Your Name");
    var email = prompt("Please write your email:","[email protected]");
    location.replace('?nombre=' + nombre + '&email=' + email);
    </script>
<?php
} else {
// AQUI INSERTAS LOS DATOS A TU BD

// PRIMERO DEBES REALIZAR LA CONEXION A LA BASE DE DATOS
mysql_connect('SERVIDOR','USUARIO','CONTRASEÑA') or die('error conectando a la bd');
mysql_select_db('NOMBRE_DE_LA_BD') or die('error seleccionando la bd');

$sql "INSERT INTO tabla (nombre, email) VALUES ('".$_GET['nombre']."','".$_GET['email']."')";
if(
mysql_query($sql)) {
echo 
'Your data has been registered!! Now you are in the contest.<br />Remember that you can try all times you want!!';
} else {
echo 
'no se insertaron los datos porque:<br />'.mysql_error();
}
}
?>
  #3 (permalink)  
Antiguo 19/05/2006, 18:30
 
Fecha de Ingreso: diciembre-2005
Ubicación: Mar del Plata
Mensajes: 146
Antigüedad: 18 años, 3 meses
Puntos: 2
muchisimas gracias okram..

voy a intentar con ese codigo...

la base de datos esta bien escrita asi?
  #4 (permalink)  
Antiguo 19/05/2006, 18:33
okram
Invitado
 
Mensajes: n/a
Puntos:
Cita:
Iniciado por cpuser
la base de datos esta bien escrita asi?
donde coloco SERVIDOR, USUARIO, CONTRASEÑA y NOMBRE_DE_LA_BD debes colocar tus datos de la base de datos...

y otra cosa:

la consulta debe seer asi

$sql = "INSERT INTO mp_usrsorteo (nombre, email) VALUES ('".$_GET['nombre']."','".$_GET['email']."')";

me equivoque en el nombre de la tabla
  #5 (permalink)  
Antiguo 20/05/2006, 08:38
 
Fecha de Ingreso: diciembre-2005
Ubicación: Mar del Plata
Mensajes: 146
Antigüedad: 18 años, 3 meses
Puntos: 2
gracias okram.. si podes contesta el mensaje privado...

si alguna otra persona quiere ayudarme le digo..

el script el cual estoy usando trabaja con archivos tpl+php

y se me hace dificilisimo insertar esto:

<?php
if(!isset($_GET['nombre']) || !isset($_GET['email'])) {
?>
<script language="javascript" type="text/javascript">
alert('The pixel you selected is a winner pixel!! Please click OK to enter the contest!!\n Just fill the form with your Name and Email');
var nombre = prompt("Please write your name:","Your Name");
var email = prompt("Please write your email:","[email protected]");
location.replace('?nombre=' + nombre + '&email=' + email);
</script>

porque si pongo

<?php
if(!isset($_GET['nombre']) || !isset($_GET['email'])) {
?>
en alguna parte del php y
<script language="javascript" type="text/javascript">
alert('The pixel you selected is a winner pixel!! Please click OK to enter the contest!!\n Just fill the form with your Name and Email');
var nombre = prompt("Please write your name:","Your Name");
var email = prompt("Please write your email:","[email protected]");
location.replace('?nombre=' + nombre + '&email=' + email);
</script>

en la parte del tpl me salta error :s...

y nose como solucionarlo

espero que me puedan ayudar
  #6 (permalink)  
Antiguo 20/05/2006, 10:29
okram
Invitado
 
Mensajes: n/a
Puntos:
Usando AJAX -.-

Hola, aqui tienes el codigo que diseñe tal como me lo pediste por el PM... estoy usando AJAX para guardar los datos en la BD... pruebalo y comentas

esto en tu tpl clicks.tpl, entre el {if $clicks_ganador} y su correspondiente cierre {/if}:

Código:
{literal}
<script language="javascript" type="text/javascript">

function guardar_datos(nombre,email)
{
        try {
                xmlvar = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
                try {
                        xmlvar = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (E) {
                        xmlvar = false;
                }
        }
        if (!xmlvar && typeof XMLHttpRequest!='undefined') {
                xmlvar = new XMLHttpRequest();
        }
    _values_send="&nombre=" + nombre + "&email=" + email;
    xmlvar_URL="reg.php?guardar";
    xmlvar.open("POST",xmlvar_URL,true);
    xmlvar.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xmlvar.send(_values_send);
    xmlvar.onreadystatechange=function() {
        if (xmlvar.readyState==4)
        {
            if(xmlvar.status==200)
            {
              alert(xmlvar.responseText);
              location.replace('index.php');
            }
        }
    }
}

alert('The pixel you selected is a winner pixel!! Please click OK to enter the contest!!\n Just fill the form with your Name and Email');

var nombre = prompt("Please write your name:","Your Name");
var email = prompt("Please write your email:","[email protected]");

guardar_datos(nombre,email);
</script>
{/literal}
Ahi esta el script en JS que te mostrara primero un alert diciendo que eres el ganador, luego te pedira nombre y email, y pasara estos datos a una pagina reg.php en la que deberas colocar esto:

Código PHP:
<?php
if(isset($_GET['guardar'])) {
// AQUI GUARDAMOS LOS DATOS A LA BD

// PRIMERO DEBES REALIZAR LA CONEXION A LA BASE DE DATOS
@mysql_connect('SERVIDOR','USUARIO','CONTRASEÑA') or die('Error conectando a la bd');
@
mysql_select_db('NOMBRE_DE_LA_BD') or die('Error seleccionando la bd');

$sql "INSERT INTO mp_usrsorteo (nombre, email) VALUES 

('"
.$_POST['nombre']."','".$_POST['email']."')";
if(
mysql_query($sql)) {
// AQUI EL MENSAJE QUE SALDRA EN UN ALERT ANTES DE QUE SE REDIRECCIONE AL INDEX
echo 'Your data has been registered!! (Name:'.$_POST['nombre'].' - Email: '.$_POST['email'].')\n 

Now you are in the contest.\nRemember that you can try all times you want!!'
;
} else {
echo 
'No se insertaron los datos porque: '.mysql_error();
}

}
?>
me parece que asi esta bien tanto codigo marea

Editado:

Añade
{literal} y {/literal} antes y despues del script respectiuvamente para que el sistema de templates Smarty, que es el que tu usas, reconozca el javascript

Última edición por okram; 20/05/2006 a las 10:51 Razón: corregido CUATRO veces.... vere si llego a 5 correcciones xD
  #7 (permalink)  
Antiguo 20/05/2006, 10:54
 
Fecha de Ingreso: diciembre-2005
Ubicación: Mar del Plata
Mensajes: 146
Antigüedad: 18 años, 3 meses
Puntos: 2
muchisimas gracias okram! sos un genio :D...

solucionaste mi peor error =)...

ahora una preguntita...

para hacer un random en una tabla...

tengo que usar esto?:

SELECT nombre, mail FROM Tabla ORDER BY RANDOM LIMIT 0,1 ?
  #8 (permalink)  
Antiguo 20/05/2006, 11:01
okram
Invitado
 
Mensajes: n/a
Puntos:
para seleccionar un registro de manera aleatoria puedes hacer esto:

Código PHP:
<?php

// PRIMERO DEBES REALIZAR LA CONEXION A LA BASE DE DATOS
@mysql_connect('SERVIDOR','USUARIO','PASS') or die('Error conectando a la bd');
@
mysql_select_db('BASE_DE_DATOS') or die('Error seleccionando la bd');

// HALLAS EL NUMERO TOTAL DE REGISTROS
$sql mysql_query("SELECT * FROM mp_usrsorteo");
$total mysql_num_rows($sql);

// HALLAS UN NUMERO ALEATORIO QUE ESTE COMPRENDIDO ENTRE
// 1 Y EL HNUMERO TOTAL DE REGS
$nrand rand(1,$total);

// RECOGES LOS DATOS DEL GANADOR
$result mysql_query("SELECT * FROM mp_usrsorteo WHERE id='".$nrand."' LIMIT 0,1");
$winners mysql_num_rows($result);

// LISTO
if($winners == 1) {
$datos mysql_fetch_assoc($result);

$nombre $datos['nombre'];
$email $datos['email'];
$id $datos['id'];

echo 
'El ganador tiene el id '.$id.' que le corresponde a '.$nombre.' ('.$email.')';

}

?>
  #9 (permalink)  
Antiguo 20/05/2006, 11:18
 
Fecha de Ingreso: diciembre-2005
Ubicación: Mar del Plata
Mensajes: 146
Antigüedad: 18 años, 3 meses
Puntos: 2
wijaaaaaaaaaaaaaa sos un capo okram :D!
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 17:45.