Foros del Web » Programando para Internet » PHP »

Problema con carga desde formulario

Estas en el tema de Problema con carga desde formulario en el foro de PHP en Foros del Web. Hola... tengo que cargar productos desde un formulario a una base de datos.. estos tmb van con una img... la carga de productos me funcionaba ...
  #1 (permalink)  
Antiguo 28/07/2008, 11:22
 
Fecha de Ingreso: julio-2008
Mensajes: 14
Antigüedad: 15 años, 8 meses
Puntos: 0
Problema con carga desde formulario

Hola... tengo que cargar productos desde un formulario a una base de datos.. estos tmb van con una img... la carga de productos me funcionaba bien hasta que trate de hacer carga de img... en este momento me tira este error:

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') VALUES ('aca va el producto', 'la descripcion', 1, 1, 1, 234)' at line 1"

los tres valores 1 son de un menu desplegable y 234 es el valor del producto.

aca el codigo de la web...


Código PHP:
<?php
if (!isset($_SESSION)) {
  
session_start();
}
$MM_authorizedUsers "1";
$MM_donotCheckaccess "false";

// *** 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 == "") && false) { 
      
$isValid true
    } 
  } 
  return 
$isValid
}

$MM_restrictGoTo "../../index.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 ""
{
  
$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"] == "form1")) {
  
$insertSQL sprintf("INSERT INTO productos (producto, descripcion, estado, categoria, mayorista, valor,) VALUES (%s, %s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['producto'], "text"),                    
                       
GetSQLValueString($_POST['descripcion'], "text"),
                       
GetSQLValueString($_POST['estado'], "int"),
                       
GetSQLValueString($_POST['categoria'], "int"),
                       
GetSQLValueString($_POST['mayorista'], "int"),
                       
GetSQLValueString($_POST['valor'], "int"));
                     
                    

  
mysql_select_db($database_cnx$cnx);
  
$Result1 mysql_query($insertSQL$cnx) or die(mysql_error());

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

mysql_select_db($database_cnx$cnx);
$query_rsd_producto "SELECT MAX(id_producto) as id_producto FROM productos";
$rsd_producto mysql_query($query_rsd_producto$cnx) or die(mysql_error());
$row_rsd_producto mysql_fetch_assoc($rsd_producto);
$totalRows_rsd_producto mysql_num_rows($rsd_producto);

mysql_select_db($database_cnx$cnx);
$query_estados "SELECT * FROM estados";
$estados mysql_query($query_estados$cnx) or die(mysql_error());
$row_estados mysql_fetch_assoc($estados);
$totalRows_estados mysql_num_rows($estados);

mysql_select_db($database_cnx$cnx);
$query_categorias "SELECT * FROM categorias";
$categorias mysql_query($query_categorias$cnx) or die(mysql_error());
$row_categorias mysql_fetch_assoc($categorias);
$totalRows_categorias mysql_num_rows($categorias);

mysql_select_db($database_cnx$cnx);
$query_mayorista "SELECT * FROM mayorista";
$mayorista mysql_query($query_mayorista$cnx) or die(mysql_error());
$row_mayorista mysql_fetch_assoc($mayorista);
$totalRows_mayorista mysql_num_rows($mayorista);


?>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Agregar Producto</title>


</head>


<body>
<?php if (!isset ($_GET['cargo'])){ ?>
<p><span class="style2">PASO 1:<br />
</span><span class="style15">Agregar un producto</span></p>
<form action="<?php echo $editFormAction?>" method="post" name="form1" id="form1">
<table align="center">
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Producto:</td>
      <td><input name="producto" type="text" id="producto" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Descripcion:</td>
      <td><textarea name="descripcion" cols="32" id="descripcion"></textarea></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Valor:</td>
      <td><input name="valor" type="integer" id="valor" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Estado:</td>
      <td><select name="estado" id="id_estado">
        <?php
do {  
?><option value="<?php echo $row_estados['id_estado']?>"><?php echo $row_estados['estado']?></option>
        <?php
} while ($row_estados mysql_fetch_assoc($estados));
  
$rows mysql_num_rows($estados);
  if(
$rows 0) {
      
mysql_data_seek($estados0);
      
$row_estados mysql_fetch_assoc($estados);
  }
?>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Categoria:</td>
      <td><select name="categoria" id="categoria">
        <?php
do {  
?>
        <option value="<?php echo $row_categorias['id_categoria']?>"><?php echo $row_categorias['categoria']?></option>
        <?php
} while ($row_categorias mysql_fetch_assoc($categorias));
  
$rows mysql_num_rows($categorias);
  if(
$rows 0) {
      
mysql_data_seek($categorias0);
      
$row_categorias mysql_fetch_assoc($categorias);
  }
?>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Mayorista:</td>
      <td><select name="mayorista" id="mayorista">
          <?php
do {  
?>
          <option value="<?php echo $row_mayorista['id_mayorista']?>"><?php echo $row_mayorista['mayorista']?></option>
          <?php
} while ($row_mayorista mysql_fetch_assoc($mayorista));
  
$rows mysql_num_rows($mayorista);
  if(
$rows 0) {
      
mysql_data_seek($mayorista0);
      
$row_mayorista mysql_fetch_assoc($mayorista);
  }
?>
        </select>      </td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">&nbsp;</td>
      <td><input type="submit" onClick="MM_validateForm('producto','','R','descripcion','','R','valor','','R');return document.MM_returnValue" value="Siguiente" /></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1" />
</form>
<p>&nbsp;</p>
<p>
  <?php }else{ ?>
</p>
<p>&nbsp; </p>
<p>&nbsp;</p>

<p>&nbsp; </p>
<p align="left"><span class="style2">PASO 2:<br />
</span><span class="style15">Subir la foto del producto</span></p>
<p>
<form action="../../imagen2.php" method="post" enctype="multipart/form-data" name="foto" id="form2">
  <label>
  <input name="archivo" type="file" class="style30" />
  </p>
  <p>
    <input name="submit" type="submit" class="style30" id="submit" value="enviar" />
  <label></label></p>
</form>
<?php ?>
</body>
</html>
<?php
mysql_free_result
($rsd_producto);

mysql_free_result($estados);

mysql_free_result($categorias);

mysql_free_result($mayorista);


?>


Si me pueden ayudar se los agradezco!!!
  #2 (permalink)  
Antiguo 28/07/2008, 14:08
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Problema con carga desde formulario

Tienes una coma de mas despues de valor en tu query.

Saludos.
  #3 (permalink)  
Antiguo 07/08/2008, 20:01
 
Fecha de Ingreso: julio-2008
Mensajes: 14
Antigüedad: 15 años, 8 meses
Puntos: 0
Respuesta: Problema con carga desde formulario

Muchas Gracias GatorV... Me Sirvio y ademas arregle un par de cositas mas q tenia mal... el problema es q ahora avanzando de a poco en este raro lenguaje de php... me tira este error cuando quiero cargar la img del producto...

Warning: imagejpeg() [function.imagejpeg]: Unable to open 'img/7.jpg' for writing: No such file or directory in C:\wamp\www\Down01\Admin\Productos\imagen2.php on line 110


el código de image2.php es...

Código PHP:
<?php require_once('../../Connections/cnx.php'); ?><?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  
$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;
}
}

mysql_select_db($database_cnx$cnx);
$query_rsd_id_usuario "SELECT MAX(id_usuario) as id_usuario FROM login";
$rsd_id_usuario mysql_query($query_rsd_id_usuario$cnx) or die(mysql_error());
$row_rsd_id_usuario mysql_fetch_assoc($rsd_id_usuario);
$totalRows_rsd_id_usuario mysql_num_rows($rsd_id_usuario);
?>
<?php
//variables
$nombre=$_FILES['archivo']['name'];
$archivo_size=$_FILES['archivo']['size'];
$archivo_type=$_FILES['archivo']['type'];
$info getimagesize($_FILES['archivo']['tmp_name']);
$ruta="img/";
$limite="si";
$size="25000";
$tipo1="image/jpeg";
$tipo2="image/gif";
$tipo3="image/png";


if (
$archivo_type==$tipo1){
$nombre $row_rsd_id_usuario['id_usuario'].".jpg";
}
if (
$archivo_type==$tipo2){
$nombre $row_rsd_id_usuario['id_usuario'].".gif";
}
if (
$archivo_type==$tipo3){
$nombre $row_rsd_id_usuario['id_usuario'].".png";
}

// Obtenemos la información de la imagen
$im_info getimagesize($_FILES['archivo'] ['tmp_name']);
// Evaluamos si es GIF(1) o JPEG(2)
// y creamos la imagen en GD
switch($im_info[2]) {
  case 
1:
    
$imagen imagecreatefromgif($_FILES['archivo'] ['tmp_name']); 
    
    break;
  case 
2:
    
$imagen imagecreatefromjpeg($_FILES['archivo'] ['tmp_name']);
    
     break;
  case 
3:
    
$imagen imagecreatefrompng($_FILES['archivo'] ['tmp_name'])
    
    ; break;
  
// etcétera //
  
}
  

// Definimos la medida máxima
$th_max 120// de la muestra (thumbnail)

// Evaluamos si la imagen es horizontal
if($im_info[0]>$im_info[1]) {
    
// Definimos las medidas de las imagenes
    
$th_w $th_max;
    
$th_h = ($im_info[1]/$im_info[0])*$th_max;
   
    } else {
    
$th_w = ($im_info[0]/$im_info[1])*$th_max;
    
$th_h $th_max;
   
    }

// Creamos las imágenes
$thumb imagecreatetruecolor($th_w,$th_h);


// Copiamos la original escalada
imagecopyresampled($thumb,$imagen,0,0,0,0$th_w,$th_h,imagesx($imagen),imagesy($imagen));



// Destruimos la imagen original
imagedestroy($imagen);

    
// Damos salida a nuestros archivos
imagejpeg($thumb,$ruta.$nombre,60);


// Destruimos las imagenes temporales
imagedestroy($thumb);

 
//header(sprintf("Location: %s", "dos.php"));
 
$log.="";
 if (
$nombre == ""){
    
$log.="No se seleccionó ningún archivo";
    }

                    if (
file_exists($ruta.$nombre)){
                        
$log.= "El archivo se subió con éxito";
                        

                
                    }else{
                        
$log.="No es un archivo autorizado";
                        }
                    
?>
<p align="center"><span class="style1"><?php echo $log ?></span></p>
<p><a href="Productos.php">volver a productos</a></p>
<p><a href="imagen1.php">intentar nuevamente</a></p>
<p class="style1">&nbsp;</p>
</body>

</html>
<?php
mysql_free_result
($rsd_id_usuario);
?>
y en verdad... no entiendo nada ya que mi fasinacion es con el 3d y la animacion... esto lo hago por obligacion... Y no entiendo nada!!!!!!!!!!!!!

Gracias! Nuevamente!!

Última edición por lanbinder; 07/08/2008 a las 20:05 Razón: estaba mal el copiado
  #4 (permalink)  
Antiguo 07/08/2008, 20:42
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Problema con carga desde formulario

Hola lanbinder,

El error te indica que no existe la carpeta/archivo que quieres abrir, revisa que exista.

Saludos.
  #5 (permalink)  
Antiguo 08/08/2008, 12:28
 
Fecha de Ingreso: julio-2008
Mensajes: 14
Antigüedad: 15 años, 8 meses
Puntos: 0
Respuesta: Problema con carga desde formulario

SI!!!! Muchisimas Gracias!! y por la rapidez de las respuestas!!!!

La ultima.... Todas las Img se me suben con el nombre "7.jpg"... Me gustaria poder cargarlas con el nombre de ip de cada producto... y en el listado no puedo conseguir q se vean mas q los nombres.... estuve viendo el foro pero no lo encontre....

y gracias de nuevoo!!!
  #6 (permalink)  
Antiguo 08/08/2008, 13:19
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Problema con carga desde formulario

A la hora de subir tu foto, ponle el nombre que debe de usar.

Saludos.
  #7 (permalink)  
Antiguo 08/08/2008, 14:10
 
Fecha de Ingreso: julio-2008
Mensajes: 14
Antigüedad: 15 años, 8 meses
Puntos: 0
Respuesta: Problema con carga desde formulario

NO.. poruqe en realidad lo q hace es Examinar y buscar una cualquiera... lo que necesito saber es cuando le modifica el tamaño y que se yo.. le ponga de nombre el ip_producto del producto q estoy cargando.. pero me las carga todas con el mismo nombre....
Ademas el nombre de la imagen cargada para el roducto no se me carga en la base de datos... todos los otros datos si....

Última edición por lanbinder; 08/08/2008 a las 14:14 Razón: Correcciones y aclaraciones
  #8 (permalink)  
Antiguo 08/08/2008, 14:13
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Problema con carga desde formulario

Sin ver el código ni como realizas el proceso es dificil asesorarte, pero la solución ahí esta, el segundo parámetro cuando usas copy() o move_uploaded_file() es el nombre destino de la imagen, ahí tu puedes especificar que use ese nombre.

Saludos.
  #9 (permalink)  
Antiguo 08/08/2008, 14:19
 
Fecha de Ingreso: julio-2008
Mensajes: 14
Antigüedad: 15 años, 8 meses
Puntos: 0
Respuesta: Problema con carga desde formulario

Ok, Gracias igual.. probare y mirare... igualmente los codigos de los dos archivos (imgen1.php y imagen2.php ) estan en el posteo... Gracias por la atencion!
  #10 (permalink)  
Antiguo 08/08/2008, 14:34
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Respuesta: Problema con carga desde formulario

Si te fijas al crear el "thumb", usas $nombre de variable, y más arriba de tu código le asignas a $nombre el valor que te envia el usuario, si tu lo cambias ahi por otra cosa, se cambiará el nombre de la imagen al subir.

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 06:03.