Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] Insertar datos uno por uno en tabla MYSQL

Estas en el tema de Insertar datos uno por uno en tabla MYSQL en el foro de PHP en Foros del Web. Hola, navegando por el foro encontré un script muy útil que subió el usuario Truman Truman. La verdad me está siendo muy útil para lo ...
  #1 (permalink)  
Antiguo 22/08/2013, 17:33
dankko
Invitado
 
Mensajes: n/a
Puntos:
Insertar datos uno por uno en tabla MYSQL

Hola, navegando por el foro encontré un script muy útil que subió el usuario Truman Truman.

La verdad me está siendo muy útil para lo que deseo hacer, pero me queda un último paso en el que estoy trabado.

El script se trata de un generador de jornadas de fútbol. Aquí mostraré el script limpió para que sea más entendible y todos sepan lo que quiero hacer.

Código PHP:
Ver original
  1. <?php
  2. /*
  3.  * This code owes an enormous debt to
  4.  * http://www.barrychessclub.org.uk/berger2001.htm
  5.  */
  6.  
  7. function main() {
  8.     ?>
  9.     <style>
  10.     input, textarea { display: block; margin-bottom: 1em; }
  11.     label { font-weight: bold; display: block; }
  12.     </style>
  13.     <h1>Fixtures Generator</h1>
  14.     <p>This page is part of <a
  15.     href="http://bluebones.net/2005/05/league-fixtures-generator/">bluebones.net</a>.</p>
  16.     <?php
  17.     // Find out how many teams we want fixtures for.
  18.     if (! isset($_GET['teams']) && ! isset($_GET['names'])) {
  19.         print get_form();
  20.     } else {
  21.         # XXX check for int
  22.        print show_fixtures(isset($_GET['teams']) ?  nums(intval($_GET['teams'])) : explode("\n", trim($_GET['names'])));
  23.     }
  24. }
  25.  
  26. function nums($n) {
  27.     $ns = array();
  28.     for ($i = 1; $i <= $n; $i++) {
  29.         $ns[] = $i;
  30.     }
  31.     return $ns;
  32. }
  33.  
  34. function show_fixtures($names) {
  35.     $teams = sizeof($names);
  36.  
  37.     print "<p>Jornadas para $teams equipos.</p>";
  38.  
  39.     // If odd number of teams add a "ghost".
  40.     $ghost = false;
  41.     if ($teams % 2 == 1) {
  42.         $teams++;
  43.         $ghost = true;
  44.     }
  45.    
  46.     // Generate the fixtures using the cyclic algorithm.
  47.     $totalRounds = $teams - 1;
  48.     $matchesPerRound = $teams / 2;
  49.     $rounds = array();
  50.     for ($i = 0; $i < $totalRounds; $i++) {
  51.         $rounds[$i] = array();
  52.     }
  53.    
  54.     for ($round = 0; $round < $totalRounds; $round++) {
  55.         for ($match = 0; $match < $matchesPerRound; $match++) {
  56.             $home = ($round + $match) % ($teams - 1);
  57.             $away = ($teams - 1 - $match + $round) % ($teams - 1);
  58.             // Last team stays in the same place while the others
  59.             // rotate around it.
  60.             if ($match == 0) {
  61.                 $away = $teams - 1;
  62.             }
  63.             $rounds[$round][$match] = team_name($home + 1, $names)
  64.                 . " v " . team_name($away + 1, $names);
  65.         }
  66.     }
  67.  
  68.     // Interleave so that home and away games are fairly evenly dispersed.
  69.     $interleaved = array();
  70.     for ($i = 0; $i < $totalRounds; $i++) {
  71.         $interleaved[$i] = array();
  72.     }
  73.    
  74.     $evn = 0;
  75.     $odd = ($teams / 2);
  76.     for ($i = 0; $i < sizeof($rounds); $i++) {
  77.         if ($i % 2 == 0) {
  78.             $interleaved[$i] = $rounds[$evn++];
  79.         } else {
  80.             $interleaved[$i] = $rounds[$odd++];
  81.         }
  82.     }
  83.  
  84.     $rounds = $interleaved;
  85.  
  86.     // Last team can't be away for every game so flip them
  87.     // to home on odd rounds.
  88.     for ($round = 0; $round < sizeof($rounds); $round++) {
  89.         if ($round % 2 == 1) {
  90.             $rounds[$round][0] = flip($rounds[$round][0]);
  91.         }
  92.     }
  93.    
  94.     // Display the fixtures        
  95.     for ($i = 0; $i < sizeof($rounds); $i++) {
  96.         print "<p>Jornada " . ($i + 1) . "</p>\n";
  97.         foreach ($rounds[$i] as $r) {
  98.             print $r . "<br />";
  99.         }
  100.         print "<br />";
  101.     }
  102.     print "<p>Second half is mirror of first half</p>";
  103.     $round_counter = sizeof($rounds) + 1;
  104.     for ($i = sizeof($rounds) - 1; $i >= 0; $i--) {
  105.         print "<p>Round " . $round_counter . "</p>\n";
  106.         $round_counter += 1;
  107.         foreach ($rounds[$i] as $r) {
  108.             print flip($r) . "<br />";
  109.         }
  110.         print "<br />";
  111.     }
  112.     print "<br />";
  113.  
  114.     if ($ghost) {
  115.         print "Matches against team " . $teams . " are byes.";
  116.     }
  117. }
  118.  
  119. function flip($match) {
  120.     $components = explode(' v ', $match);
  121.     return $components[1] . " v " . $components[0];
  122. }
  123.  
  124. function team_name($num, $names) {
  125.     $i = $num - 1;
  126.     if (sizeof($names) > $i && strlen(trim($names[$i])) > 0) {
  127.         return trim($names[$i]);
  128.     } else {
  129.         return $num;
  130.     }
  131. }
  132.  
  133. function get_form() {
  134.     $s = '';
  135.  
  136.     $s .= '<form action="' . $_SERVER['SCRIPT_NAME'] . '">' . "\n";
  137.     $s .= '<label for="names">Introducir el ID de los equipos participantes (uno por linea)</label>'
  138.         . '<textarea name="names" rows="8" cols="40">
  139. 106
  140. 108
  141. 111
  142. 113
  143. 116
  144. 119
  145. 123
  146. 133
  147. 141
  148. 143
  149. 145
  150. 147        
  151.         </textarea>' . "\n";
  152.     $s .= '<input type="submit" value="Generate Fixtures" />' . "\n";
  153.     $s .= "</form>\n";
  154.     return $s;
  155. }
  156.  
  157. main();
  158.  
  159. ?>

Vale, pongámonos en el caso de que yo tengo una tabla en mi base de datos muy simple llamada "matches":

id_round (primary, auto)
round
away
home


Aquí viene mi duda que es la siguiente:

Quiero insertar un partido por fila, pero la verdad, es que no se de que forma hacer el insert ni en que lugar colocarlo.

Código PHP:
Ver original
  1. $ssql ="insert  into matches (round,home,away)  values ('" . $round. "','" . $home. "','" . $away. "')";
  2.       if (mysql_query($ssql)){
  3.             echo '<span class="label label-success">¡Partido insertado correctamente!</span>';
  4.       }else{
  5.             echo '<span class="label label-important">¡Ha habido un error!</span>';
  6.       }

Estas es la función que cree para insertar los partidos, pero al autogenerar el calendario con los partidos, tan sólo hace una inserción vacía en la base de datos.

Espero que alguien pueda guiarme con esto. Muchas gracias.
  #2 (permalink)  
Antiguo 24/08/2013, 01:20
dankko
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Insertar datos uno por uno en tabla MYSQL

He probado de esta manera pero sigue insertándome un único registro vacío:

Código PHP:
Ver original
  1. <?php
  2.     /*
  3.      * This code owes an enormous debt to
  4.      * http://www.barrychessclub.org.uk/berger2001.htm
  5.      */
  6.      
  7.     function main() {
  8.         ?>
  9.         <style>
  10.         input, textarea { display: block; margin-bottom: 1em; }
  11.         label { font-weight: bold; display: block; }
  12.         </style>
  13.         <h1>Fixtures Generator</h1>
  14.         <p>This page is part of <a
  15.         href="http://bluebones.net/2005/05/league-fixtures-generator/">bluebones.net</a>.</p>
  16.         <?php
  17.         // Find out how many teams we want fixtures for.
  18.         if (! isset($_GET['teams']) && ! isset($_GET['names'])) {
  19.             print get_form();
  20.         } else {
  21.             # XXX check for int
  22.            print show_fixtures(isset($_GET['teams']) ?  nums(intval($_GET['teams'])) : explode("\n", trim($_GET['names'])));
  23.         }
  24.     }
  25.      
  26.     function nums($n) {
  27.         $ns = array();
  28.         for ($i = 1; $i <= $n; $i++) {
  29.             $ns[] = $i;
  30.         }
  31.         return $ns;
  32.     }
  33.      
  34.     function show_fixtures($names) {
  35.         $teams = sizeof($names);
  36.      
  37.         print "<p>Jornadas para $teams equipos.</p>";
  38.      
  39.         // If odd number of teams add a "ghost".
  40.         $ghost = false;
  41.         if ($teams % 2 == 1) {
  42.             $teams++;
  43.             $ghost = true;
  44.         }
  45.        
  46.         // Generate the fixtures using the cyclic algorithm.
  47.         $totalRounds = $teams - 1;
  48.         $matchesPerRound = $teams / 2;
  49.         $rounds = array();
  50.         for ($i = 0; $i < $totalRounds; $i++) {
  51.             $rounds[$i] = array();
  52.         }
  53.        
  54.         for ($round = 0; $round < $totalRounds; $round++) {
  55.             for ($match = 0; $match < $matchesPerRound; $match++) {
  56.                 $home = ($round + $match) % ($teams - 1);
  57.                 $away = ($teams - 1 - $match + $round) % ($teams - 1);
  58.                 // Last team stays in the same place while the others
  59.                 // rotate around it.
  60.                 if ($match == 0) {
  61.                     $away = $teams - 1;
  62.                 }
  63.                 $rounds[$round][$match] = team_name($home + 1, $names)
  64.                     . " v " . team_name($away + 1, $names);
  65.             }
  66.         }
  67.      
  68.         // Interleave so that home and away games are fairly evenly dispersed.
  69.         $interleaved = array();
  70.         for ($i = 0; $i < $totalRounds; $i++) {
  71.             $interleaved[$i] = array();
  72.         }
  73.        
  74.         $evn = 0;
  75.         $odd = ($teams / 2);
  76.         for ($i = 0; $i < sizeof($rounds); $i++) {
  77.             if ($i % 2 == 0) {
  78.                 $interleaved[$i] = $rounds[$evn++];
  79.             } else {
  80.                 $interleaved[$i] = $rounds[$odd++];
  81.             }
  82.         }
  83.      
  84.         $rounds = $interleaved;
  85.      
  86.         // Last team can't be away for every game so flip them
  87.         // to home on odd rounds.
  88.         for ($round = 0; $round < sizeof($rounds); $round++) {
  89.             if ($round % 2 == 1) {
  90.                 $rounds[$round][0] = flip($rounds[$round][0]);
  91.             }
  92.         }
  93.        
  94.         // Display the fixtures        
  95.         for ($i = 0; $i < sizeof($rounds); $i++) {
  96.             print "<p>Jornada " . ($i + 1) . "</p>\n";
  97.             foreach ($rounds[$i] as $r) {
  98.                 print $r . "<br />";
  99.             }
  100.             print "<br />";
  101.         }
  102.         print "<p>Second half is mirror of first half</p>";
  103.         $round_counter = sizeof($rounds) + 1;
  104.         for ($i = sizeof($rounds) - 1; $i >= 0; $i--) {
  105.             print "<p>Round " . $round_counter . "</p>\n";
  106.             $round_counter += 1;
  107.             foreach ($rounds[$i] as $r) {
  108.                 print flip($r) . "<br />";
  109.             }
  110.             print "<br />";
  111.         }
  112.         print "<br />";
  113.      
  114.         if ($ghost) {
  115.             print "Matches against team " . $teams . " are byes.";
  116.         }
  117.     }
  118.      
  119.     function flip($match) {
  120.         $components = explode(' v ', $match);
  121.         return $components[1] . " v " . $components[0];
  122.     }
  123.      
  124.     function team_name($num, $names) {
  125.         $i = $num - 1;
  126.         if (sizeof($names) > $i && strlen(trim($names[$i])) > 0) {
  127.             return trim($names[$i]);
  128.         } else {
  129.             return $num;
  130.         }
  131.     }
  132.      
  133.     function get_form() {
  134.         $s = '';
  135.      
  136.         $s .= '<form action="' . $_SERVER['SCRIPT_NAME'] . '">' . "\n";
  137.         $s .= '<label for="names">Introducir el ID de los equipos participantes (uno por linea)</label>'
  138.             . '<textarea name="names" rows="8" cols="40">
  139.    106
  140.    108
  141.    111
  142.    113
  143.    116
  144.    119
  145.    123
  146.    133
  147.    141
  148.    143
  149.    145
  150.    147        
  151.            </textarea>' . "\n";
  152.         $s .= '<input type="submit" value="Generate Fixtures" />' . "\n";
  153.         $s .= "</form>\n";
  154.         return $s;
  155.     }
  156.      
  157.     main();
  158.  
  159. $ssql ="insert  into matches (round,home,away)  values ('" . $round. "','" . $home. "','" . $away. "')";
  160.       if (mysql_query($ssql)){
  161.             echo '<span class="label label-success">¡Partido insertado correctamente!</span>';
  162.       }else{
  163.             echo '<span class="label label-important">¡Ha habido un error!</span>';
  164.      
  165.     ?>
  #3 (permalink)  
Antiguo 26/08/2013, 17:14
dankko
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Insertar datos uno por uno en tabla MYSQL

Alguien tiene alguna idea de donde en que parte podria poner la sentencia para insertar los valores? tendría que usar algun "for"? La verdad no se por donde cogerlo...
  #4 (permalink)  
Antiguo 27/08/2013, 07:47
Avatar de loncho_rojas
Colaborador
 
Fecha de Ingreso: octubre-2008
Ubicación: En el mejor lugar del mundo
Mensajes: 2.704
Antigüedad: 15 años, 6 meses
Puntos: 175
Respuesta: Insertar datos uno por uno en tabla MYSQL

No se donde exactamente porque ni siquiera podemos ver de donde vienen los valores, si tienes varios forms y esas cosas.. lo ideal serían 2 cosas, pero no pasan de una abstracción mia...

Guardas todos los valores en un array y despues los vas insertando con un for each...

otra opción es contar con el COUNT cuantos registros fueron enviados y con un bucle FOR vas haciendo los insert...
__________________
Ayudo con lo que puedo en el foro, y solo en el foro.. NO MENSAJES PRIVADOS.. NO EMAILS NI SKYPE u OTROS.

Antes de hacer un TOPICO piensa si puedes hallarlo en Google o en el Buscador del Foro...
  #5 (permalink)  
Antiguo 27/08/2013, 08:16
dankko
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Insertar datos uno por uno en tabla MYSQL

Lo que hago es pasarle los IDs de cada equipo para generar el partido, estos los saco a través de una consulta indicándole antes de que campeonato se trata. No lo puse entero por simplificar el trabajo y no tener que explicar todo, pudiendolo explicar de manera errónea y que no se me entendiera.

Vamos a probar así a ver si se entiende mejor:

Código PHP:
Ver original
  1. <?php
  2.         /*
  3.          * This code owes an enormous debt to
  4.          * http://www.barrychessclub.org.uk/berger2001.htm
  5.          */
  6.          
  7.         function main() {
  8.             ?>
  9.             <style>
  10.             input, textarea { display: block; margin-bottom: 1em; }
  11.             label { font-weight: bold; display: block; }
  12.             </style>
  13.             <h1>Fixtures Generator</h1>
  14.             <p>This page is part of <a
  15.             href="http://bluebones.net/2005/05/league-fixtures-generator/">bluebones.net</a>.</p>
  16.             <?php
  17.             // Find out how many teams we want fixtures for.
  18.             if (! isset($_GET['teams']) && ! isset($_GET['names'])) {
  19.                 print get_form();
  20.             } else {
  21.                 # XXX check for int
  22.                print show_fixtures(isset($_GET['teams']) ?  nums(intval($_GET['teams'])) : explode("\n", trim($_GET['names'])));
  23.             }
  24.         }
  25.          
  26.         function nums($n) {
  27.             $ns = array();
  28.             for ($i = 1; $i <= $n; $i++) {
  29.                 $ns[] = $i;
  30.             }
  31.             return $ns;
  32.         }
  33.          
  34.         function show_fixtures($names) {
  35.             $teams = sizeof($names);
  36.          
  37.             print "<p>Jornadas para $teams equipos.</p>";
  38.          
  39.             // If odd number of teams add a "ghost".
  40.             $ghost = false;
  41.             if ($teams % 2 == 1) {
  42.                 $teams++;
  43.                 $ghost = true;
  44.             }
  45.            
  46.             // Generate the fixtures using the cyclic algorithm.
  47.             $totalRounds = $teams - 1;
  48.             $matchesPerRound = $teams / 2;
  49.             $rounds = array();
  50.             for ($i = 0; $i < $totalRounds; $i++) {
  51.                 $rounds[$i] = array();
  52.             }
  53.            
  54.             for ($round = 0; $round < $totalRounds; $round++) {
  55.                 for ($match = 0; $match < $matchesPerRound; $match++) {
  56.                     $home = ($round + $match) % ($teams - 1);
  57.                     $away = ($teams - 1 - $match + $round) % ($teams - 1);
  58.                     // Last team stays in the same place while the others
  59.                     // rotate around it.
  60.                     if ($match == 0) {
  61.                         $away = $teams - 1;
  62.                     }
  63.                     $rounds[$round][$match] = team_name($home + 1, $names)
  64.                         . " v " . team_name($away + 1, $names);
  65.                 }
  66.             }
  67.          
  68.             // Interleave so that home and away games are fairly evenly dispersed.
  69.             $interleaved = array();
  70.             for ($i = 0; $i < $totalRounds; $i++) {
  71.                 $interleaved[$i] = array();
  72.             }
  73.            
  74.             $evn = 0;
  75.             $odd = ($teams / 2);
  76.             for ($i = 0; $i < sizeof($rounds); $i++) {
  77.                 if ($i % 2 == 0) {
  78.                     $interleaved[$i] = $rounds[$evn++];
  79.                 } else {
  80.                     $interleaved[$i] = $rounds[$odd++];
  81.                 }
  82.             }
  83.          
  84.             $rounds = $interleaved;
  85.          
  86.             // Last team can't be away for every game so flip them
  87.             // to home on odd rounds.
  88.             for ($round = 0; $round < sizeof($rounds); $round++) {
  89.                 if ($round % 2 == 1) {
  90.                     $rounds[$round][0] = flip($rounds[$round][0]);
  91.                 }
  92.             }
  93.            
  94.             // Display the fixtures        
  95.             for ($i = 0; $i < sizeof($rounds); $i++) {
  96.                 print "<p>Jornada " . ($i + 1) . "</p>\n";
  97.                 foreach ($rounds[$i] as $r) {
  98.                     print $r . "<br />";
  99.                 }
  100.                 print "<br />";
  101.             }
  102.             print "<p>Second half is mirror of first half</p>";
  103.             $round_counter = sizeof($rounds) + 1;
  104.             for ($i = sizeof($rounds) - 1; $i >= 0; $i--) {
  105.                 print "<p>Round " . $round_counter . "</p>\n";
  106.                 $round_counter += 1;
  107.                 foreach ($rounds[$i] as $r) {
  108.                     print flip($r) . "<br />";
  109.                 }
  110.                 print "<br />";
  111.             }
  112.             print "<br />";
  113.          
  114.             if ($ghost) {
  115.                 print "Matches against team " . $teams . " are byes.";
  116.             }
  117.         }
  118.          
  119.         function flip($match) {
  120.             $components = explode(' v ', $match);
  121.             return $components[1] . " v " . $components[0];
  122.         }
  123.          
  124.         function team_name($num, $names) {
  125.             $i = $num - 1;
  126.             if (sizeof($names) > $i && strlen(trim($names[$i])) > 0) {
  127.                 return trim($names[$i]);
  128.             } else {
  129.                 return $num;
  130.             }
  131.         }
  132.          
  133.         function get_form() {
  134.             $s = '';
  135.          
  136.             $s .= '<form action="' . $_SERVER['SCRIPT_NAME'] . '">' . "\n";
  137.             $s .= '<label for="names">Introducir el ID de los equipos participantes (uno por linea)</label>'
  138.                 . '<textarea name="names" rows="8" cols="40">
  139.       FC Barcelona
  140.       Real Madrid
  141.       Valencia CF
  142.       Sevilla
  143.       Osasuna
  144.       Málaga
  145.       Celta
  146.       Villarreal
  147.       Granada
  148.       Atlético de Madrid
  149.       Getafe
  150.       Althetic Club
  151.               </textarea>' . "\n";
  152.             $s .= '<input type="submit" value="Generate Fixtures" />' . "\n";
  153.             $s .= "</form>\n";
  154.             return $s;
  155.         }
  156.          
  157.         main();
  158.      
  159.     $ssql ="insert  into matches (round,home,away)  values ('" . $round. "','" . $home. "','" . $away. "')";
  160.           if (mysql_query($ssql)){
  161.                 echo '<span class="label label-success">¡Partido insertado correctamente!</span>';
  162.           }else{
  163.                 echo '<span class="label label-important">¡Ha habido un error!</span>';
  164.          
  165.         ?>

Pongámos que ya generé los equipos con los que quiero que se realice el emparejamiento.

Como podría utilizar el foreach aquí? No logro entenderlo por mucho que leo, no entiendo muy bien el proceso que realiza.

Etiquetas: futbol, partidos, registros, tabla
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 01:33.