Foros del Web » Programando para Internet » PHP »

Insert en un While

Estas en el tema de Insert en un While en el foro de PHP en Foros del Web. Hola, Tengo esta inserción Código PHP: if (  $archivo  !=  "none"  ){       //CREAMOS NUESTRO INSERT      $array = array( $_POST [ "tag" ]);     foreach(  $array  as  $valor  ) { ...
  #1 (permalink)  
Antiguo 05/03/2012, 14:30
Avatar de dvbeaumont  
Fecha de Ingreso: marzo-2011
Ubicación: Caracas
Mensajes: 145
Antigüedad: 13 años, 1 mes
Puntos: 1
Exclamación Insert en un While

Hola,

Tengo esta inserción

Código PHP:
if ( $archivo != "none" ){

     
//CREAMOS NUESTRO INSERT
    
$array= array($_POST["tag"]);
    foreach( 
$array as $valor ) {
    while (
$valor != ""){ 
    
$qry "INSERT INTO t_tag_articulo (id_tag, id_articulo) VALUES
    (  '"
.$valor."', '".$_POST["id_articulo"]."')";
                      }
                                }
    
//NOS CONECAMOS A LA BASE DE DATOS
    //REMPLAZEN SUS VALOS POR LOS MIOS
mysql_connect("localhost"," "," ") or die("No se pudo conectar a la base de datos");
    
    
//SELECCIONAMOS LA BASE DE DATOS CON LA CUAL VAMOS A TRABAJAR CAMBIEN EL VALOR POR LA SUYA
mysql_select_db(" ");
    
    
//EJECUTAMOS LA CONSULTA
    
mysql_query($qry) or die("Query: $qry <br />Error: ".mysql_error());
    
    
//CERRAMOS LA CONEXION
    
mysql_close();
    
//NOTIFICAMOS AL USUARIO QUE EL ARCHVO SE HA ENVIADO O REDIRIGIMOS A OTRO LADO ETC.
    
echo "    <script language=javascript>
    alert('Comentario hecho satisfactoriamente')
    </script>"
;
    include_once (
"lista-articulos.php");
}else{
    echo 
"    <script language=javascript>
    alert('No fue posible cargar el comentario, intente de nuevo')
    </script>"
;
    include_once (
"lista-articulos.php");

Pero parece que se queda pegado con los datos y el formulario es este:

Código HTML:
Ver original
  1. <form id="form" action="upload-tagarticulo.php"  enctype="multipart/form-data" method="post" autocomplete="off">
  2.                     <fieldset>
  3.                         <section>
  4.                             <label for="multiselect">Tags <br><span><a href='cargar-tag.php'>Crear nuevo </a></span></label>
  5.                             <div>                  
  6.                                 <select name="tag[]" id="multiselect" multiple>
  7.                                         <?php
  8.                             $result_ti=mysql_query("select * from t_tag ORDER BY id_tag",$link);                           
  9.                             while($row_t = mysql_fetch_array($result_ti)) {
  10.                             echo"<option value='".$row_t["id_tag"]."'>".$row_t["titulo"]."</option>";}
  11.                             ?>
  12.                             </select>
  13.                             </div>
  14.                         </section>
  15.                         <input type='hidden' name="id_articulo"  value='<?php echo"".$row[0].""?>' />
  16.                         <section>
  17.                             <div><button class="reset">Reset</button><button class="submit" name="submitbuttonname" value="submitbuttonvalue">Enviar</button></div>
  18.                         </section>
  19.                     </fieldset>
  20.                 </form>

Teniendo en cuenta que el select HTML es tag[] para enviar todos los tags que seleccione.
__________________
Sé parte de nuestro mundo creativo.

http://bbcreativos.com
  #2 (permalink)  
Antiguo 05/03/2012, 14:35
Avatar de roal40  
Fecha de Ingreso: enero-2012
Mensajes: 61
Antigüedad: 12 años, 3 meses
Puntos: 4
Respuesta: Insert en un While

No seria...

if($valor != ""){

Vamos... yo siempre he usado if... no he probado con un while...
  #3 (permalink)  
Antiguo 05/03/2012, 14:37
Avatar de dvbeaumont  
Fecha de Ingreso: marzo-2011
Ubicación: Caracas
Mensajes: 145
Antigüedad: 13 años, 1 mes
Puntos: 1
Respuesta: Insert en un While

Pero yo lo que quiero es insertar varios datos en mysql desde un select multiple.

el while es para hacer el loop hasta que reconozca que ya no hay mas datos que insertar, pero al parecer se queda pegado porque nunca termina la funcion.
__________________
Sé parte de nuestro mundo creativo.

http://bbcreativos.com
  #4 (permalink)  
Antiguo 05/03/2012, 15:12
Avatar de DooBie  
Fecha de Ingreso: septiembre-2004
Mensajes: 1.101
Antigüedad: 19 años, 7 meses
Puntos: 71
Respuesta: Insert en un While

Si pones el foreach y el while como lo tienes ahora, y tal y como te dice roal40, del while no saldrá.
Quita el while, y deja solo el foreach, ya verás como funciona.
  #5 (permalink)  
Antiguo 05/03/2012, 15:17
Avatar de dvbeaumont  
Fecha de Ingreso: marzo-2011
Ubicación: Caracas
Mensajes: 145
Antigüedad: 13 años, 1 mes
Puntos: 1
Respuesta: Insert en un While

Así?

Código PHP:
Ver original
  1. $array= array($_POST['tag']);
  2.     foreach( $array as $valor ) {
  3.     $qry = "INSERT INTO t_tag_articulo (id_tag, id_articulo) VALUES
  4.     (  '".$valor."', '".$_POST["id_articulo"]."')";
  5.                                 }

Pues aun no envia sino un solo registro... Lo que me hace dudar es el html

Cuando hago el combobox debe ser asi?

Código HTML:
Ver original
  1. <form id="form" action="upload-tagarticulo.php"  enctype="multipart/form-data" method="post" autocomplete="off">
  2.                                    
  3.                                 <select name="tag[]" id="multiselect" multiple>
  4.                                         <?php
  5.                             $result_ti=mysql_query("select * from t_tag ORDER BY id_tag",$link);                           
  6.                             while($row_t = mysql_fetch_array($result_ti)) {
  7.                             echo"<option value='".$row_t["id_tag"]."'>".$row_t["titulo"]."</option>";}
  8.                             ?>
  9.                             </select>
  10.                 </form>
__________________
Sé parte de nuestro mundo creativo.

http://bbcreativos.com
  #6 (permalink)  
Antiguo 05/03/2012, 16:02
Avatar de DooBie  
Fecha de Ingreso: septiembre-2004
Mensajes: 1.101
Antigüedad: 19 años, 7 meses
Puntos: 71
Respuesta: Insert en un While

Claro que sólo te guarda un registro, de hecho, sólo te guarda el último.

Código PHP:
$qry .= "INSERT INTO t_tag_articulo (id_tag, id_articulo) VALUES
    (  '"
.$valor."', '".$_POST["id_articulo"]."');"
Prueba con esa línea.
  #7 (permalink)  
Antiguo 05/03/2012, 16:18
Avatar de dvbeaumont  
Fecha de Ingreso: marzo-2011
Ubicación: Caracas
Mensajes: 145
Antigüedad: 13 años, 1 mes
Puntos: 1
Respuesta: Insert en un While

Pues parece que si esta tomando los datos pero mira lo que me genera:

Mi html es:

Código HTML:
Ver original
  1. <form id="form" action="upload-tagarticulo.php"  enctype="multipart/form-data" method="post" autocomplete="off">
  2.                     <fieldset>
  3.                         <section>
  4.                             <label for="multiselect">Tags <br><span><a href='cargar-tag.php'>Crear nuevo </a></span></label>
  5.                             <div>                  
  6.                                 <select name="tag[]" id="multiselect" multiple>
  7.                                         <?php
  8.                             $result_ti=mysql_query("select * from t_tag ORDER BY id_tag",$link);                           
  9.                             while($row_t = mysql_fetch_array($result_ti)) {
  10.                             echo"<option value='".$row_t["id_tag"]."'>".$row_t["titulo"]."</option>";}
  11.                             ?>
  12.                             </select>
  13.                             </div>
  14.                         </section>
  15.                         <input type='hidden' name='id_articulo' value='<?php echo"".$row[0].""?>' />
  16.                         <section>
  17.                             <div><button class="reset">Reset</button><button class="submit" name="submitbuttonname" value="submitbuttonvalue">Enviar</button></div>
  18.                         </section>
  19.                     </fieldset>
  20.                 </form>

el php es

Código PHP:
Ver original
  1. //VERIFICAMOS DE NUEVO QUE SE SELECCIONO ALGUN ARCHIVO
  2. if ( $archivo != "none" ){
  3.  
  4.     //CREAMOS NUESTRO INSERT
  5.     foreach( $_POST['tag'] as $valor ) {
  6.     $qry .= "INSERT INTO t_tag_articulo (id_tag, id_articulo) VALUES
  7.    (  '".$valor."', '".$_POST["id_articulo"]."');";  
  8.                                 }
  9.                                
  10.                                
  11.                              
  12.  
  13.     //NOS CONECAMOS A LA BASE DE DATOS
  14.     //REMPLAZEN SUS VALOS POR LOS MIOS
  15. mysql_connect("localhost"," "," ") or die("No se pudo conectar a la base de datos");
  16.    
  17.     //SELECCIONAMOS LA BASE DE DATOS CON LA CUAL VAMOS A TRABAJAR CAMBIEN EL VALOR POR LA SUYA
  18.    
  19.     //EJECUTAMOS LA CONSULTA
  20.     mysql_query($qry) or die("Query: $qry <br />Error: ".mysql_error());
  21.    
  22.     //CERRAMOS LA CONEXION
  23.     mysql_close();
  24.     //NOTIFICAMOS AL USUARIO QUE EL ARCHVO SE HA ENVIADO O REDIRIGIMOS A OTRO LADO ETC.
  25.     echo "  <script language=javascript>
  26.     alert('Comentario hecho satisfactoriamente')
  27.     </script>";
  28.     include_once ("lista-articulos.php");
  29. }else{
  30.     echo "  <script language=javascript>
  31.     alert('No fue posible cargar el comentario, intente de nuevo')
  32.     </script>";
  33.     include_once ("lista-articulos.php");
  34. }

y el error que da es:

Query: INSERT INTO t_tag_articulo (id_tag, id_articulo) VALUES ( '1', '16');INSERT INTO t_tag_articulo (id_tag, id_articulo) VALUES ( '2', '16');INSERT INTO t_tag_articulo (id_tag, id_articulo) VALUES ( '3', '16');INSERT INTO t_tag_articulo (id_tag, id_articulo) VALUES ( '4', '16');INSERT INTO t_tag_articulo (id_tag, id_articulo) VALUES ( '5', '16');
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 'INSERT INTO t_tag_articulo (id_tag, id_articulo) VALUES ( '2', '16');INSER' at line 2

Pero no veo cual es...
__________________
Sé parte de nuestro mundo creativo.

http://bbcreativos.com

Etiquetas: formulario, html, insert, mysql, 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 13:25.