Foros del Web » Programando para Internet » PHP »

No guarda usuario en BD

Estas en el tema de No guarda usuario en BD en el foro de PHP en Foros del Web. Hola a todos! Bueno les cuento..estoy creando un carro de compras, el cual esta casi teerminado, pero tengo 2 problemas al precionar el boton "comprar" ...
  #1 (permalink)  
Antiguo 11/07/2009, 20:25
Avatar de karen_7  
Fecha de Ingreso: febrero-2009
Mensajes: 12
Antigüedad: 15 años, 2 meses
Puntos: 0
No guarda usuario en BD

Hola a todos!

Bueno les cuento..estoy creando un carro de compras, el cual esta casi teerminado, pero tengo 2 problemas al precionar el boton "comprar" en mi pagina producto.php ,esto pasa cuando ya se esta viendo el producto que se quiere subir al carro:

1.- al presionar el boton comprar , se devuelve a la pagina de los productos (frutas.php,verduras.php)y no muestra boleta.php, que es donde se debiera ir el producto para ir calculando la suma de todos los productos seleccionados para comprar.


2.- al presionar el boton comprar se guardan en la BD los datos del producto en mi tabla "compras", pero no queda almacenado el nombre del usuario, solo los datos del producto.

EN mi BD tengo 3 tablas, con los sgtes campos:

a..- tabla catalogo : id,producto,precio,catgoria,frase_promocinal,descr ipcion,promocion,etc.

b.- tabla cliente : id,nombre,apellido,mail,telefono,sector,direccion, usuario,clave.

c.- tabla compras :id, usuario,codigo,producto,precio,cantidad,fecha.

A continuacion agrego el todo el codigo de la pagina productos.php

Código PHP:
<?php require_once('Connections/carro.php'); ?>
<?php
if (!isset($_SESSION)) {
  
session_start();
}
$MM_authorizedUsers "";
$MM_donotCheckaccess "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers$strGroups$UserName$UserGroup) { 
  
// For security, start by assuming the visitor is NOT authorized. 
  
$isValid False

  
// When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  
if (!empty($UserName)) { 
    
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    
$arrUsers Explode(","$strUsers); 
    
$arrGroups Explode(","$strGroups); 
    if (
in_array($UserName$arrUsers)) { 
      
$isValid true
    } 
    
// Or, you may restrict access to only certain users based on their username. 
    
if (in_array($UserGroup$arrGroups)) { 
      
$isValid true
    } 
    if ((
$strUsers == "") && true) { 
      
$isValid true
    } 
  } 
  return 
$isValid
}

$MM_restrictGoTo "login.php";
if (!((isset(
$_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers$_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  
$MM_qsChar "?";
  
$MM_referrer $_SERVER['PHP_SELF'];
  if (
strpos($MM_restrictGoTo"?")) $MM_qsChar "&";
  if (isset(
$QUERY_STRING) && strlen($QUERY_STRING) > 0
  
$MM_referrer .= "?" $QUERY_STRING;
  
$MM_restrictGoTo $MM_restrictGoTo$MM_qsChar "accesscheck=" urlencode($MM_referrer);
  
header("Location: "$MM_restrictGoTo); 
  exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  if (
PHP_VERSION 6) {
    
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  
$theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch (
$theType) {
    case 
"text":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;    
    case 
"long":
    case 
"int":
      
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case 
"double":
      
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case 
"date":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;
    case 
"defined":
      
$theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}

$editFormAction $_SERVER['PHP_SELF'];
if (isset(
$_SERVER['QUERY_STRING'])) {
  
$editFormAction .= "?" htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "compra")) {
  
$insertSQL sprintf("INSERT INTO compras (codigo, producto, precio, cantidad) VALUES (%s, %s, %s, %s)",
                       
GetSQLValueString($_POST['codigo'], "text"),
                       
GetSQLValueString($_POST['producto'], "text"),
                       
GetSQLValueString($_POST['precio'], "double"),
                       
GetSQLValueString($_POST['cantidad'], "int"));

  
mysql_select_db($database_carro$carro);
  
$Result1 mysql_query($insertSQL$carro) or die(mysql_error());

  
$insertGoTo "boleta.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}


if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "compra")) {
  
$insertSQL sprintf("INSERT INTO compras (codigo, producto, precio, cantidad) VALUES (%s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['codigo'], "text"),                       
                       
GetSQLValueString($_POST['producto'], "text"),
                       
GetSQLValueString($_POST['precio'], "double"),
                       
GetSQLValueString($_POST['cantidad'], "int"));

  
mysql_select_db($database_carro$carro);
  
$Result1 mysql_query($insertSQL$carro) or die(mysql_error());
  
  
$insertGoTo "boleta.php";
  
//echo isset($_SERVER['QUERY_STRING']);
  /*if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }*/
  //echo $insertGoTo;
  
header(sprintf("Location: %s"$insertGoTo));
}

$colname_producto "1";
if (isset(
$_GET['id'])) {
  
$colname_producto $_GET['id'];
}
mysql_select_db($database_carro$carro);
$query_producto sprintf("SELECT * FROM catalogo WHERE id = %s"GetSQLValueString($colname_producto"int"));
$producto mysql_query($query_producto$carro) or die(mysql_error());
$row_producto mysql_fetch_assoc($producto);
$totalRows_producto mysql_num_rows($producto);

$colname_cliente "-1";
if (isset(
$_GET['MM_Username'])) {
  
$colname_cliente $_GET['MM_Username'];
}
mysql_select_db($database_carro$carro);
$query_cliente sprintf("SELECT * FROM cliente WHERE usuario = %s"GetSQLValueString($colname_cliente"text"));
$cliente mysql_query($query_cliente$carro) or die(mysql_error());
$row_cliente mysql_fetch_assoc($cliente);
$totalRows_cliente mysql_num_rows($cliente);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "1/DTD/xhtml1-transitional.dtd">
<html xmlns=".../xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="carro.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
    color: #000;
}
-->
</style></head>
<body leftmargin="200" topmargin="25" marginwidth="250" marginheight="40">
<div id="contenido">

  <h2>Código Producto:    
    <?php  echo $row_producto['codigo']; ?></h2>
  <div id="producto">
    <p><?php echo $row_cliente['usuario']; ?></p>
    <p><strong><img name="" src="images/<?php echo $row_producto['codigo']; ?>.jpg" width="233" height="200" alt="" /></strong></p>
    <table width="95" height="33" border="0">
      <tr>
        <td><strong><span style="float:right">
          <? if ($row_producto['promocion'] =="1") {echo "¡OFERTA!" ;} ?>
        </span></strong></td>
      </tr>
    </table>
    <p><strong><?php echo $row_producto['producto']; ?></strong></p>
    <p><strong><?php echo $row_producto['frase_promocional']; ?></strong></p>
    <p><strong><span style="float:right">      </span></strong>
    </p>
    <p><strong><?php echo nl2br($row_producto['descripcion']); ?></strong></p>
    <p>&nbsp;</p>
    <form action="<?php echo $editFormAction?>" id="compra" name="compra" method="POST">
      <table width="392" border="0" align="center">
        <tr>
          <td colspan="3" align="left"> <strong>Precio:</strong><strong> $ <?php echo $row_producto['precio']; ?></strong></td>
        </tr>
        <tr>
          <td width="200"><label for="cantidad3">cantidad </label><input name="cantidad" type="text" id="cantidad3" value="1" size="3" maxlength="3" /> 
            <?php echo $row_prueba['unidad']; ?></td>
          
          <td width="134">
          <input name="precio" type="hidden" id="precio" value="<?php echo $row_producto['precio']; ?>" />
        <input name="codigo" type="hidden" id="codigo" value="<?php echo $row_producto['codigo']; ?>" />
        <input name="producto" type="hidden" id="producto" value="<?php echo $row_producto['producto']; ?>" />
        <input name="usuario" type="hidden" id="usuario" value="<?php echo $row_cliente['usuario']; ?>" />
        <input type="submit" name="comprar" id="comprar" value="comprar" />
          <input type="hidden" name="MM_insert" value="compra" /></td>
        </tr>
      </table>
      <p>&nbsp;</p>
      <p><a href="<?php echo $row_producto['categoria']; ?>">Volver a Lista de Productos</a>
        <?php if($_SESSION['MM_Username']){?>
      </p>
      <p><a href="logout.php">Cerrar Sesión</a>
        <?php } else {?>
      </p>
      <p><a href="registro.php">registro</a>
        <?php }?>
      </p>
</form>
  </div>
</div>
</body>
</html>
<?php
mysql_free_result
($producto);

mysql_free_result($cliente);
?>

Ojala puedan ayudarme,se lo agradezceria mucho,ya que no se cual es el problema de esas 2 cosas... Muchas gracias desde ya,saludos,Adios!!
  #2 (permalink)  
Antiguo 11/07/2009, 20:33
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: No guarda usuario en BD

bueno, eso se debe porque efectivamente no estas siquiera tratando de insertar el usuario...

según tu código solo insertas cuatro cosas:
Código PHP:
"INSERT INTO compras (codigo, producto, precio, cantidad) VALUES (%s, %s, %s, %s, %s)" 
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 13/07/2009, 14:15
Avatar de karen_7  
Fecha de Ingreso: febrero-2009
Mensajes: 12
Antigüedad: 15 años, 2 meses
Puntos: 0
Respuesta: No guarda usuario en BD

Hola gracias por tu respuesta .. pero sabes? no paso absolutamente nada.. cambie el valor de usuario en la BD de not null a null.. pero nada.. eñ codigo quedo asi actualmente :


Código PHP:
<?php require_once('Connections/carro.php'); ?>
<?php
if (!isset($_SESSION)) {
  
session_start();
}
$MM_authorizedUsers "";
$MM_donotCheckaccess "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers$strGroups$UserName$UserGroup) { 
  
// For security, start by assuming the visitor is NOT authorized. 
  
$isValid False

  
// When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  
if (!empty($UserName)) { 
    
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    
$arrUsers Explode(","$strUsers); 
    
$arrGroups Explode(","$strGroups); 
    if (
in_array($UserName$arrUsers)) { 
      
$isValid true
    } 
    
// Or, you may restrict access to only certain users based on their username. 
    
if (in_array($UserGroup$arrGroups)) { 
      
$isValid true
    } 
    if ((
$strUsers == "") && true) { 
      
$isValid true
    } 
  } 
  return 
$isValid
}

$MM_restrictGoTo "login.php";
if (!((isset(
$_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers$_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  
$MM_qsChar "?";
  
$MM_referrer $_SERVER['PHP_SELF'];
  if (
strpos($MM_restrictGoTo"?")) $MM_qsChar "&";
  if (isset(
$QUERY_STRING) && strlen($QUERY_STRING) > 0
  
$MM_referrer .= "?" $QUERY_STRING;
  
$MM_restrictGoTo $MM_restrictGoTo$MM_qsChar "accesscheck=" urlencode($MM_referrer);
  
header("Location: "$MM_restrictGoTo); 
  exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  if (
PHP_VERSION 6) {
    
$theValue get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  
$theValue function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch (
$theType) {
    case 
"text":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;    
    case 
"long":
    case 
"int":
      
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case 
"double":
      
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case 
"date":
      
$theValue = ($theValue != "") ? "'" $theValue "'" "NULL";
      break;
    case 
"defined":
      
$theValue = ($theValue != "") ? $theDefinedValue $theNotDefinedValue;
      break;
  }
  return 
$theValue;
}
}

$editFormAction $_SERVER['PHP_SELF'];
if (isset(
$_SERVER['QUERY_STRING'])) {
  
$editFormAction .= "?" htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "compra")) {
  
$insertSQL sprintf("INSERT INTO compras (codigo, usuario, producto, precio, cantidad) VALUES (%s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['codigo'], "text"),
                       
GetSQLValueString($_POST['usuario'], "text"),
                       
GetSQLValueString($_POST['producto'], "text"),
                       
GetSQLValueString($_POST['precio'], "double"),
                       
GetSQLValueString($_POST['cantidad'], "int"));

  
mysql_select_db($database_carro$carro);
  
$Result1 mysql_query($insertSQL$carro) or die(mysql_error());

  
$insertGoTo "boleta.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}


if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "compra")) {
  
$insertSQL sprintf("INSERT INTO compras (codigo, producto, precio, cantidad) VALUES (%s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['codigo'], "text"),
                       
GetSQLValueString($_POST['usuario'], "text"),
                       
GetSQLValueString($_POST['producto'], "text"),
                       
GetSQLValueString($_POST['precio'], "double"),
                       
GetSQLValueString($_POST['cantidad'], "int"));

  
mysql_select_db($database_carro$carro);
  
$Result1 mysql_query($insertSQL$carro) or die(mysql_error());
  
  
$insertGoTo "boleta.php";
  
//echo isset($_SERVER['QUERY_STRING']);
  /*if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }*/
  //echo $insertGoTo;
  
header(sprintf("Location: %s"$insertGoTo));
}

$colname_producto "1";
if (isset(
$_GET['id'])) {
  
$colname_producto $_GET['id'];
}
mysql_select_db($database_carro$carro);
$query_producto sprintf("SELECT * FROM catalogo WHERE id = %s"GetSQLValueString($colname_producto"int"));
$producto mysql_query($query_producto$carro) or die(mysql_error());
$row_producto mysql_fetch_assoc($producto);
$totalRows_producto mysql_num_rows($producto);

$colname_cliente "1";
if (isset(
$_GET['MM_Username'])) {
  
$colname_cliente $_GET['MM_Username'];
}
mysql_select_db($database_carro$carro);
$query_cliente sprintf("SELECT * FROM cliente WHERE usuario = %s"GetSQLValueString($colname_cliente"text"));
$cliente mysql_query($query_cliente$carro) or die(mysql_error());
$row_cliente mysql_fetch_assoc($cliente);
$totalRows_cliente mysql_num_rows($cliente);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="carro.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
body,td,th {
    font-size: 12px;
    color: #000;
}
-->
</style></head>
<body leftmargin="200" topmargin="25" marginwidth="250" marginheight="40">
<div id="contenido">

  <h2>Código Producto:    
    <?php  echo $row_producto['codigo']; ?></h2>
  <div id="producto">
    <p><?php echo $row_cliente['usuario']; ?></p>
    <p><strong><img name="" src="images/<?php echo $row_producto['codigo']; ?>.jpg" width="233" height="200" alt="" /></strong></p>
    <table width="95" height="33" border="0">
      <tr>
        <td><strong><span style="float:right">
          <? if ($row_producto['promocion'] =="1") {echo "¡OFERTA!" ;} ?>
        </span></strong></td>
      </tr>
    </table>
    <p><strong><?php echo $row_producto['producto']; ?></strong></p>
    <p><strong><?php echo $row_producto['frase_promocional']; ?></strong></p>
    <p><strong><span style="float:right">      </span></strong>
    </p>
    <p><strong><?php echo nl2br($row_producto['descripcion']); ?></strong></p>
    <p>&nbsp;</p>
    <form action="<?php echo $editFormAction?>" id="compra" name="compra" method="POST">
      <table width="392" border="0" align="center">
        <tr>
          <td colspan="3" align="left"> <strong>Precio:</strong><strong> $ <?php echo $row_producto['precio']; ?></strong></td>
        </tr>
        <tr>
          <td width="200"><label for="cantidad3">cantidad </label><input name="cantidad" type="text" id="cantidad3" value="1" size="3" maxlength="3" /> 
            <?php echo $row_prueba['unidad']; ?></td>
          
          <td width="134">
          <input name="precio" type="hidden" id="precio" value="<?php echo $row_producto['precio']; ?>" />
        <input name="codigo" type="hidden" id="codigo" value="<?php echo $row_producto['codigo']; ?>" />
        <input name="producto" type="hidden" id="producto" value="<?php echo $row_producto['producto']; ?>" />
        <input name="usuario" type="hidden" id="usuario" value="<?php echo $row_cliente['usuario']; ?>" />
        <input type="submit" name="comprar" id="comprar" value="comprar" />
          <input type="hidden" name="MM_insert" value="compra" /></td>
        </tr>
      </table>
      <p>&nbsp;</p>
      <p><a href="<?php echo $row_producto['categoria']; ?>">Volver a Lista de Productos</a>
        <?php if($_SESSION['MM_Username']){?>
      </p>
      <p><a href="logout.php">Cerrar Sesión</a>
        <?php } else {?>
      </p>
      <p><a href="registro.php">registro</a>
        <?php }?>
      </p>
</form>
  </div>
</div>
</body>
</html>
<?php
mysql_free_result
($producto);

mysql_free_result($cliente);
?>
Cualquier ayuda sirve..muchas gracias a todos!! :),saludos!
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 11:36.