Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] Duplicidad de adjuntos

Estas en el tema de Duplicidad de adjuntos en el foro de PHP en Foros del Web. Hola , Hasta ahora estoy empezando con programación, en mi empresa tienen una aplicación para guardar archivos, me solicitaron la misma aplicación pero para otra ...
  #1 (permalink)  
Antiguo 22/12/2015, 08:02
 
Fecha de Ingreso: noviembre-2015
Mensajes: 21
Antigüedad: 8 años, 4 meses
Puntos: 0
Duplicidad de adjuntos

Hola ,

Hasta ahora estoy empezando con programación, en mi empresa tienen una aplicación para guardar archivos, me solicitaron la misma aplicación pero para otra área, hice algunas modificaciones y todo estaba bien hasta que adjunte el archivo en uno de los registros, la falla que se me esta presentando es que al adjuntar un archivo, este me aparece en todos los registros que tengo.

EJ: si adjunto un archivo en el registro llamado cam, este mismo adjunto me queda en el registro cam2, cam 3 , etc

Relaciono el codigo que tengo del adjunto:
Código PHP:
<?php require_once('../../Connections/comercio_electronico.php'); ?>
<?php
session_start
();
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;
}
}

$colname_user "-1";
if (isset(
$_SESSION['usuario'])) {
  
$colname_user $_SESSION['usuario'];
}
mysql_select_db($database_comercio_electronico$comercio_electronico);
$query_user sprintf("SELECT * FROM grupos_usuarios WHERE usuario = %s"GetSQLValueString($colname_user"text"));
$user mysql_query($query_user$comercio_electronico) or die(mysql_error());
$row_user mysql_fetch_assoc($user);
$totalRows_user mysql_num_rows($user);


?><?php
if (isset($_SESSION['usuario'])){
     if(
$row_user['nombre']==NULL){
     
header('Location: login.php');
     }else{
     }
}else{
      
header('Location: login.php');
}
      
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Grupos - Contratos</title>
<style type="text/css">
<!--
body {
    margin-left: 0px;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 0px;
    background-color: #EAEAEA;
}
-->
</style>
<link href="../../css/clases.css" rel="stylesheet" type="text/css" />
<link href="../../css/evo_mew.css" rel="stylesheet" type="text/css" />
<link href="../../css/styles_new.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.style2 {color: #FFFFFF; }
a:link {
    color: #FF0000;
    text-decoration: none;
}
a:visited {
    text-decoration: none;
    color: #FF0000;
}
a:hover {
    text-decoration: underline;
    color: #FF0000;
}
a:active {
    text-decoration: none;
    color: #FF0000;
}
-->
</style>
<script src="../../js/jquery-1.4.4.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="../../css/prettyPhoto.css" type="text/css" media="screen" title="prettyPhoto main stylesheet" charset="utf-8" />
        <script src="../../js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">
  $(document).ready(function(){
    $("a[rel^='prettyPhoto']").prettyPhoto();
  });
</script>
<script src="js/jquery.js" type="text/javascript"></script>
    <script src="js/documentation.js" type="text/javascript"></script>
 <link href="documentation.css" type="text/css" rel="stylesheet"/>
 <!--// code-highlighting //-->
    <script type="text/javaScript" src="/jquery/project/chili/jquery.chili-2.0.js"></script> 
    <script type="text/javaScript" src="/jquery/project/chili-toolbar/jquery.chili-toolbar.pack.js"></script> 
 <script type="text/javascript">try{ChiliBook.recipeFolder="/jquery/project/chili/"}catch(e){}</script>
 <!--// plugin-specific resources //-->
 <script src="js/jquery.form.js" type="text/javascript" language="javascript"></script>
    <script src="js/jquery.MetaData.js" type="text/javascript" language="javascript"></script>
 <script src="js/jquery.MultiFile.js" type="text/javascript" language="javascript"></script>
 <script src="js/jquery.blockUI.js" type="text/javascript" language="javascript"></script>
 <script language="JavaScript">
function pregunta(){
    return confirm('¿Estas seguro de borrar este adjunto?'); 
}
</script> 
</head>

<body>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td valign="middle"><div align="center">
      <table width="500" border="1">
        <tr>
          <td width="429"><form action="adjuntosg.php?id_contrato=<?PHP echo $_GET['id_contrato'];?>" method="post" enctype="multipart/form-data" name="form1">
            <p>
              <input name="ffoto[]" type="file" class="multi" accept="png|gif|jpg|jpeg|pdf|doc|docx|xls|pptx|xlsx" maxlength="5" />
              <input name="id_contrato" type="hidden" id="id_contrato" value="<?PHP echo $_GET['id_contrato'];?>">
              <input type="submit" name="button" id="button" value="Agregar">
              <input name="envia" type="hidden" id="envia" value="SI">
            </p>
           <?php 
           
if($_POST['envia']=="SI"){
    
$id $_POST['id_contrato'];
        
$cuales="";
            
/// Vemos cuantos archivos hemos subido
        
$nro=count($_FILES["ffoto"]["name"]);
    if(
$nro==0){
    echo 
"<font color='#FF0000'>Seleccione un archivo</font>";
    }
    
/// Empezamos el array
    
for ($i=0$i<$nro$i++) {
    
$file_name=$_FILES["ffoto"]["name"][$i];
    
$file_size=$_FILES["ffoto"]["size"][$i];
    
$file_type=$_FILES["ffoto"]["type"][$i];
    
$idUnico time();
    if(
$file_name!=""){
        
// verifica carpeta
        
$nombre_archivo=$_POST['femail'];
        if (!
file_exists('archivos/'.$nombre_archivo)) {
            
mkdir('archivos/'.$nombre_archivo,0777);
        }
        
$path="archivos/".$nombre_archivo;     
        
// sube archivo
        
copy($_FILES["ffoto"]['tmp_name'][$i], $path.'/'.$idUnico.$file_name) ;
         
$nombre_foto=$idUnico.$file_name;
         
$consulta="insert into grupos_archivos (id_contrato, nombre, archivo) values('$id', '$file_name', '$nombre_foto')";
         
mysql_query($consulta);
          echo 
'<p align="left">El archivo <b>'.$file_name.'</b> fue subido correctamente.</p>';
        
$cuales.=$file_name." ";
        } else {
        echo 
'<br><br><p align="left"><b>Error with '.$file_name.'</b></p>';
        }
    }
           }
           
           
$colname_archivos "-1";
if (isset(
$_GET['id_contrato'])) {
  
$colname_archivos $_GET['id_contrato'];
}
mysql_select_db($database_comercio_electronico$comercio_electronico);
$query_archivos sprintf("SELECT * FROM grupos_archivos WHERE id_contrato = %s"GetSQLValueString($colname_archivos"int"));
$archivos mysql_query($query_archivos$comercio_electronico) or die(mysql_error());
$row_archivos mysql_fetch_assoc($archivos);
$totalRows_archivos mysql_num_rows($archivos);
    
?>
          </form></td>
          <td width="61" align="left" valign="top">[<a href="contratosg.php">volver</a>]</td>
        </tr>
        <?php do { ?>
          <?php if ($totalRows_archivos 0) { // Show if recordset not empty ?>
  <tr>
    <td><a href="archivos/<?php echo $row_archivos['archivo']; ?>" target="_blank"><?php echo $row_archivos['nombre']; ?></a></td>
    <td><form id="form1" name="form1" method="post" action="borrar_adjuntog.php" ONSUBMIT="return pregunta();">
      <input name="id_archivo" type="hidden" id="id_archivo" value="<?php echo $row_archivos['id']; ?>">
      <input name="image" type=image  src="../../img/icons/fail.gif" width="16" height="16" />
      <input name="id" type="hidden" id="id" value="<?php echo $row_archivos['id_contrato']; ?>">
    </form></td>
  </tr>
  <?php // Show if recordset not empty ?>
          <?php } while ($row_archivos mysql_fetch_assoc($archivos)); ?>
      </table>
    </div></td>
  </tr>
</table>
</body>
</html>
<?php
mysql_free_result
($user);

mysql_free_result($archivos);
?>
Agradezco mucho me puedan colaborar para saber que el lo que hace que aparezca en todos los registros y no solo quede en el registro al cual le adjunte.

NOTA: en la base de datos si aparece solo 1 y en el registro que corresponde
  #2 (permalink)  
Antiguo 22/12/2015, 09:53
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Duplicidad de adjuntos

Cita:
la falla que se me esta presentando es que al adjuntar un archivo, este me aparece en todos los registros que tengo
Pues el INSERT que haces sólo agregaría un registro y no tendría por qué actualizar todos los registros en tu base de datos.

Cita:
en la base de datos si aparece solo 1 y en el registro que corresponde
Entonces tu código hace lo correcto ¿exactamente cual es el problema?
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 22/12/2015, 10:51
 
Fecha de Ingreso: noviembre-2015
Mensajes: 21
Antigüedad: 8 años, 4 meses
Puntos: 0
Respuesta: Duplicidad de adjuntos

mi problema que cuando se muestra en la pagina que tengo para que los usuarios vean los archivos, el mismo adjunto aparece en todos los registros

Si veo el registro # 1 tiene el mismo adjunto que el registro #2 y el adjunto solo lo coloque para el registro #1 , pero aparece en los dos
  #4 (permalink)  
Antiguo 22/12/2015, 11:21
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Duplicidad de adjuntos

Cita:
Iniciado por ingridquevedoa Ver Mensaje
mi problema que cuando se muestra en la pagina que tengo para que los usuarios vean los archivos, el mismo adjunto aparece en todos los registros

Si veo el registro # 1 tiene el mismo adjunto que el registro #2 y el adjunto solo lo coloque para el registro #1 , pero aparece en los dos
¿Pero en la base de datos está todo bien o no?
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #5 (permalink)  
Antiguo 23/12/2015, 07:09
 
Fecha de Ingreso: noviembre-2015
Mensajes: 21
Antigüedad: 8 años, 4 meses
Puntos: 0
Respuesta: Duplicidad de adjuntos

si esta bien y no se repite , pero cuando el usuario mira los registros en todos aparece el mismo adjunto y no deberia ser asi. porque cada registro tiene diferente adjunto
  #6 (permalink)  
Antiguo 23/12/2015, 09:34
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Duplicidad de adjuntos

Cita:
Iniciado por ingridquevedoa Ver Mensaje
si esta bien y no se repite , pero cuando el usuario mira los registros en todos aparece el mismo adjunto y no deberia ser asi. porque cada registro tiene diferente adjunto
Entonces muestra dicho código.
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #7 (permalink)  
Antiguo 23/12/2015, 09:42
 
Fecha de Ingreso: noviembre-2015
Mensajes: 21
Antigüedad: 8 años, 4 meses
Puntos: 0
Respuesta: Duplicidad de adjuntos

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

$colname_user "-1";
if (isset(
$_SESSION['usuario'])) {
  
$colname_user $_SESSION['usuario'];
}
mysql_select_db($database_comercio_electronico$comercio_electronico);
$query_user sprintf("SELECT * FROM grupos_usuarios WHERE usuario = %s"GetSQLValueString($colname_user"text"));
$user mysql_query($query_user$comercio_electronico) or die(mysql_error());
$row_user mysql_fetch_assoc($user);
$totalRows_user mysql_num_rows($user);


?><?php
if (isset($_SESSION['usuario'])){
     if(
$row_user['nombre']==NULL){
     
header('Location: login.php');
     }else{
     }
}else{
      
header('Location: login.php');
}
      
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Grupos - Contratos</title>
<style type="text/css">
<!--
body {
    margin-left: 0px;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 0px;
    background-color: #EAEAEA;
}
-->
</style>
<link href="../../css/clases.css" rel="stylesheet" type="text/css" />
<link href="../../css/evo_mew.css" rel="stylesheet" type="text/css" />
<link href="../../css/styles_new.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
.style2 {color: #FFFFFF; }
a:link {
    color: #FF0000;
    text-decoration: none;
}
a:visited {
    text-decoration: none;
    color: #FF0000;
}
a:hover {
    text-decoration: underline;
    color: #FF0000;
}
a:active {
    text-decoration: none;
    color: #FF0000;
}
-->
</style>
<script src="../../js/jquery-1.4.4.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="../../css/prettyPhoto.css" type="text/css" media="screen" title="prettyPhoto main stylesheet" charset="utf-8" />
        <script src="../../js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">
  $(document).ready(function(){
    $("a[rel^='prettyPhoto']").prettyPhoto();
  });
</script>
<script src="js/jquery.js" type="text/javascript"></script>
    <script src="js/documentation.js" type="text/javascript"></script>
 <link href="documentation.css" type="text/css" rel="stylesheet"/>
 <!--// code-highlighting //-->
    <script type="text/javaScript" src="/jquery/project/chili/jquery.chili-2.0.js"></script> 
    <script type="text/javaScript" src="/jquery/project/chili-toolbar/jquery.chili-toolbar.pack.js"></script> 
 <script type="text/javascript">try{ChiliBook.recipeFolder="/jquery/project/chili/"}catch(e){}</script>
 <!--// plugin-specific resources //-->
 <script src="js/jquery.form.js" type="text/javascript" language="javascript"></script>
    <script src="js/jquery.MetaData.js" type="text/javascript" language="javascript"></script>
 <script src="js/jquery.MultiFile.js" type="text/javascript" language="javascript"></script>
 <script src="js/jquery.blockUI.js" type="text/javascript" language="javascript"></script>
 <script language="JavaScript">
function pregunta(){
    return confirm('¿Estas seguro de borrar este adjunto?'); 
}
</script> 
</head>

<body>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td valign="middle"><div align="center">
      <table width="500" border="1">
        <tr>
          <td width="429"><form action="adjuntosg.php?id_contrato=<?PHP echo $_GET['id_contrato'];?>" method="post" enctype="multipart/form-data" name="form1">
            <p>
              <input name="ffoto[]" type="file" class="multi" accept="png|gif|jpg|jpeg|pdf|doc|docx|xls|pptx|xlsx" maxlength="5" />
              <input name="id_contrato" type="hidden" id="id_contrato" value="<?PHP echo $_GET['id_contrato'];?>">
              <input type="submit" name="button" id="button" value="Agregar">
              <input name="envia" type="hidden" id="envia" value="SI">
            </p>
           <?php 
           
if($_POST['envia']=="SI"){
    
$id $_POST['id_contrato'];
        
$cuales="";
            
/// Vemos cuantos archivos hemos subido
        
$nro=count($_FILES["ffoto"]["name"]);
    if(
$nro==0){
    echo 
"<font color='#FF0000'>Seleccione un archivo</font>";
    }
    
/// Empezamos el array
    
for ($i=0$i<$nro$i++) {
    
$file_name=$_FILES["ffoto"]["name"][$i];
    
$file_size=$_FILES["ffoto"]["size"][$i];
    
$file_type=$_FILES["ffoto"]["type"][$i];
    
$idUnico time();
    if(
$file_name!=""){
        
// verifica carpeta
        
$nombre_archivo=$_POST['femail'];
        if (!
file_exists('archivos/'.$nombre_archivo)) {
            
mkdir('archivos/'.$nombre_archivo,0777);
        }
        
$path="archivos/".$nombre_archivo;     
        
// sube archivo
        
copy($_FILES["ffoto"]['tmp_name'][$i], $path.'/'.$idUnico.$file_name) ;
         
$nombre_foto=$idUnico.$file_name;
         
$consulta="insert into grupos_archivos (id_contrato, nombre, archivo) values('$id', '$file_name', '$nombre_foto')";
         
mysql_query($consulta);
          echo 
'<p align="left">El archivo <b>'.$file_name.'</b> fue subido correctamente.</p>';
        
$cuales.=$file_name." ";
        } else {
        echo 
'<br><br><p align="left"><b>Error with '.$file_name.'</b></p>';
        }
    }
           }
           
           
$colname_archivos "-1";
if (isset(
$_GET['id_contrato'])) {
  
$colname_archivos $_GET['id_contrato'];
}
mysql_select_db($database_comercio_electronico$comercio_electronico);
$query_archivos sprintf("SELECT * FROM grupos_archivos WHERE id_contrato = %s"GetSQLValueString($colname_archivos"int"));
$archivos mysql_query($query_archivos$comercio_electronico) or die(mysql_error());
$row_archivos mysql_fetch_assoc($archivos);
$totalRows_archivos mysql_num_rows($archivos);
    
?>
          </form></td>
          <td width="61" align="left" valign="top">[<a href="contratosg.php">volver</a>]</td>
        </tr>
        <?php do { ?>
          <?php if ($totalRows_archivos 0) { // Show if recordset not empty ?>
  <tr>
    <td><a href="archivos/<?php echo $row_archivos['archivo']; ?>" target="_blank"><?php echo $row_archivos['nombre']; ?></a></td>
    <td><form id="form1" name="form1" method="post" action="borrar_adjuntog.php" ONSUBMIT="return pregunta();">
      <input name="id_archivo" type="hidden" id="id_archivo" value="<?php echo $row_archivos['id']; ?>">
      <input name="image" type=image  src="../../img/icons/fail.gif" width="16" height="16" />
      <input name="id" type="hidden" id="id" value="<?php echo $row_archivos['id_contrato']; ?>">
    </form></td>
  </tr>
  <?php // Show if recordset not empty ?>
          <?php } while ($row_archivos mysql_fetch_assoc($archivos)); ?>
      </table>
    </div></td>
  </tr>
</table>
</body>
</html>
<?php
mysql_free_result
($user);

mysql_free_result($archivos);
?>
Gracias
  #8 (permalink)  
Antiguo 23/12/2015, 09:47
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Duplicidad de adjuntos

¿Y exactamente cual es la linea donde muestra el adjunto repetido?
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #9 (permalink)  
Antiguo 23/12/2015, 10:12
 
Fecha de Ingreso: noviembre-2015
Mensajes: 21
Antigüedad: 8 años, 4 meses
Puntos: 0
Respuesta: Duplicidad de adjuntos

Descripción del programa: (esto porque no puedo subir imágenes)

Tengo un programa donde el usuario crea un registro con el nombre de la empresa y adjunta un contrato de la misma.
cada empresa tiene su contrato, cada uno diferente por empresa.

El error esta en que el usuario crea el registro con el nombre de la empresa y adjunta su respectivo contrato, luego crea otro registro con otra empresa pero el adjunto de la primera empresa le aparece a la segunda empresa también siendo el contrato solo para la primera empresa


la cuestión es que no se si el código tiene alguna linea donde el programa coloque el mismo adjunto en todos los registros que subo a mi programa

  #10 (permalink)  
Antiguo 23/12/2015, 12:14
 
Fecha de Ingreso: noviembre-2015
Mensajes: 21
Antigüedad: 8 años, 4 meses
Puntos: 0
Respuesta: Duplicidad de adjuntos

ya pude, cambie en una parte de mi codigo el int por el text y ya me aparecen los adjuntos que corresponden al registro

Gracias

Etiquetas: adjuntos, duplicidad, html, mysql, registro, select, sql, usuarios
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.