Foros del Web » Programando para Internet » PHP »

[SOS] Column 'imagen' cannot be null

Estas en el tema de [SOS] Column 'imagen' cannot be null en el foro de PHP en Foros del Web. Tngo dias desarrollando un panel de control y todos los sistemas de insert han funcionado pero ahora no se pq me sale este error en ...
  #1 (permalink)  
Antiguo 07/12/2007, 12:49
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 8 meses
Puntos: 28
[SOS] Column 'imagen' cannot be null

Tngo dias desarrollando un panel de control y todos los sistemas de insert han funcionado pero ahora no se pq me sale este error en este archivo, le he dado vueltas y nada... alguien podria ayudarme a ver donde esta el error?

Gracias
Código PHP:
<?php require_once('Connections/connect.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;
}
}

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

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {

$ediciondir'images/';  
$uploaddir=$ediciondir;
if (!
is_dir($ediciondir)) {     mkdir($uploaddir0777);    }
move_uploaded_file($_FILES['imagen']['tmp_name'], $uploaddir $_FILES['imagen']['name']);    
$filename $_FILES['imagen']['name'];

  
$insertSQL sprintf("INSERT INTO productos (cat_id, marca_id, nombre, descripcion, item, precio, moneda, imagen, ficha) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['cat_id'], "int"),
                       
GetSQLValueString($_POST['marca_id'], "int"),
                       
GetSQLValueString($_POST['nombre'], "text"),
                       
GetSQLValueString($_POST['descripcion'], "text"),
                       
GetSQLValueString($_POST['item'], "text"),
                       
GetSQLValueString($_POST['precio'], "text"),
                       
GetSQLValueString($_POST['moneda'], "text"),
                       
GetSQLValueString($filename"text"),
                       
GetSQLValueString($_POST['ficha'], "text"));

  
mysql_select_db($database_connect$connect);
  
$Result1 mysql_query($insertSQL$connect) or die(mysql_error());
  
$insertGoTo "ad_pro.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
 
header(sprintf("Location: %s"$insertGoTo));
}

mysql_select_db($database_connect$connect);
$query_Recordset1 "SELECT * FROM categoria";
$Recordset1 mysql_query($query_Recordset1$connect) or die(mysql_error());
$row_Recordset1 mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 mysql_num_rows($Recordset1);

mysql_select_db($database_connect$connect);
$query_Recordset2 "SELECT * FROM marca";
$Recordset2 mysql_query($query_Recordset2$connect) or die(mysql_error());
$row_Recordset2 mysql_fetch_assoc($Recordset2);
$totalRows_Recordset2 mysql_num_rows($Recordset2);

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script language="javascript" type="text/javascript">
function validar_archivo(archivo) {
    var error_archivo;
    error_archivo=0;
      var file=archivo.value;
      
          if (file=="")
          { error_archivo=1; }
          //texto += "\n\nIngrese Foto"
            else{
             
                 // file=document.formulario.FOTO.value
               extArray = new Array(".gif",".jpg");
               // Extension de archivos permitidos
               allowSubmit = false;
                 if (!file) return;

                   while (file.indexOf("\\") != -1)
                       file = file.slice(file.indexOf("\\") + 1);
                       ext = file.slice(file.indexOf(".")).toLowerCase();
                   
                   for (var i=0; i < extArray.length; i++){
                          if (extArray[i] == ext){
                             allowSubmit = true;
                             break;
                            }
                    }

                        if (!allowSubmit) {
                         error_archivo=2;
                        // texto += "\n\nFOTO: solo admite archivo con la extensión ''gif, .jpeg , .jpg''";
                         }
                            }
                            return error_archivo;
}



</script>
<script language="JavaScript" type="text/JavaScript">
<!--
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' es requerido.\n'; }
  } 
  
  var ar;
  var ar, celest;
  ar=document.form1.imagen;
  celest=validar_archivo(ar);
  if (celest==1){errors+="- Imagen es  requerido";}
  if (celest==2){errors+="- Nota: Solo admiten archivos para la imagen con la extensión ''gif, .jpeg , .jpg'";}
  
    if (errors) alert('Han ocurrido los siguientes errores:\n'+errors);
  document.MM_returnValue = (errors == '');
}
//-->
</script>

<body>
<form action="<?php echo $editFormAction?>" method="post" enctype="multipart/form-data" name="form1" onSubmit="MM_validateForm('descripcion','','R');return document.MM_returnValue">
  <table align="center">
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Cat_id:</td>
      <td><select name="cat_id" class="todopanel">
        <?php
do {  
?>
        <option value="<?php echo $row_Recordset1['id']?>"><?php echo $row_Recordset1['nombre']?></option>
        <?php
} while ($row_Recordset1 mysql_fetch_assoc($Recordset1));
  
$rows mysql_num_rows($Recordset1);
  if(
$rows 0) {
      
mysql_data_seek($Recordset10);
      
$row_Recordset1 mysql_fetch_assoc($Recordset1);
  }
?>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Marca_id:</td>
      <td><select name="marca_id" class="todopanel">
        <?php
do {  
?>
        <option value="<?php echo $row_Recordset2['marca_id']?>"><?php echo $row_Recordset2['nombre']?></option>
        <?php
} while ($row_Recordset2 mysql_fetch_assoc($Recordset2));
  
$rows mysql_num_rows($Recordset2);
  if(
$rows 0) {
      
mysql_data_seek($Recordset20);
      
$row_Recordset2 mysql_fetch_assoc($Recordset2);
  }
?>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Nombre:</td>
      <td><input type="text" name="nombre" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Descripcion:</td>
      <td><input type="text" name="descripcion" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Item:</td>
      <td><input type="text" name="item" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Precio:</td>
      <td><input type="text" name="precio" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Moneda:</td>
      <td><input type="text" name="moneda" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Imagen:</td>
      <td><input name="imagen" type="file" class="todopanel"  enctype="multipart/form-data" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Ficha:</td>
      <td><input type="text" name="ficha" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">&nbsp;</td>
      <td><input type="submit" value="Insert record"/></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1" />
</form>
<p>&nbsp;</p>
</body>
</html>
<?php
mysql_free_result
($Recordset1);
mysql_free_result($Recordset2);
?>
  #2 (permalink)  
Antiguo 07/12/2007, 13:07
Avatar de mauled  
Fecha de Ingreso: marzo-2005
Ubicación: Cd. de México.
Mensajes: 3.001
Antigüedad: 19 años, 1 mes
Puntos: 33
Re: [SOS] Column 'imagen' cannot be null

Parece que tu variable $filename no esta debidamente inicializada que por lo que entiendo existe casos en los que no envias archivos

Lo que podrias es validar tu variable es decir:
Código PHP:
$filename $_FILES['imagen']['name'];

if(empty(
$filename))
$filename ""
Tambien te recomendaria que si este campo no es obligatorio "siempre" lo quites dentro de sus "propiedades" el NOT NULL y lo dejes simplemente como NULL

Saludillos.
  #3 (permalink)  
Antiguo 07/12/2007, 13:29
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 8 meses
Puntos: 28
Re: [SOS] Column 'imagen' cannot be null

gracias man... funciono al toque!!!!
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 04:34.