PHP - Modificar varios registros a la vez

 
Vista:
sin imagen de perfil

Modificar varios registros a la vez

Publicado por John (4 intervenciones) el 22/12/2014 07:34:25
Holaa,

soy un programador medio novato y estoy intentando realizar una actualización de varios registros de una sola vez (sin necesidad de modificarlos uno por uno), pude lograr eliminar varios a la vez con un checkbox pero cuando los modifico, quedan todos iguales al registro número 1 (no es que no se modifican ni obtengo un error).
Por ejemplo si tengo 30 registros, al hacer click quedan todos iguales al número 1, y si modifico el número 1, se modifican todos iguales al 1.
Necesitaría que me pasen la parte del código que me falta o debería modificar, graciass

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php require_once('Connections/conexionespeciales.php'); ?>
<?php
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;
}
}
 
mysql_select_db($database_conexionespeciales, $conexionespeciales);
$query_EditarFrecuentes = "SELECT intContador, tblfrecuentes.strTexto, tblfrecuentes.strRespuesta, tblfrecuentes.intEstado FROM tblfrecuentes ORDER BY tblfrecuentes.fchFecha DESC";
$EditarFrecuentes = mysql_query($query_EditarFrecuentes, $conexionespeciales) or die(mysql_error());
$row_EditarFrecuentes = mysql_fetch_assoc($EditarFrecuentes);
$totalRows_EditarFrecuentes = mysql_num_rows($EditarFrecuentes);
 
$editFormAction = $_SERVER['PHP_SELF'];
	if (isset($_SERVER['QUERY_STRING'])) {
  		$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
	}
 
?>
 
 
  <form action="<?php echo $editFormAction; ?>" method="post" name="FormEditarFrec" id="FormEditarFrec">
  <table align="center">
  <?php do { ?>
  <tr>
		<td><input name="nroReg[]" value="<?php echo $row_EditarFrecuentes['intContador']; ?>" size="1" readonly="readonly" /></td>
        <td><input type="text" name="pregunta" value="<?php echo utf8_encode($row_EditarFrecuentes['strTexto']); ?>" size="32"/></td>
		<td><input type="text" name="respuesta" value="<?php echo htmlentities(utf8_encode($row_EditarFrecuentes['strRespuesta']), ENT_COMPAT, 'utf-8'); ?>" size="32" /></td>
        <td><input type="text" name="estado" value="<?php echo htmlentities($row_EditarFrecuentes['intEstado'], ENT_COMPAT, 'utf-8'); ?>" size="2" />
        </td>
        <td><input name="Borrar[]" type="checkbox" value="<?php echo $row_EditarFrecuentes['intContador']; ?>" /></td>
   </tr>
 
   <?php
  } while ($row_EditarFrecuentes = mysql_fetch_assoc($EditarFrecuentes));  ?>
  </table>
 
    <br /><div align="center">
    <input class="boton" name="botonActualizar" type="submit" value="Actualizar registro/s" />
     <input class="boton" name="botonEliminar" type="submit" value="Borrar registro/s" /></div>
    <input type="hidden" name="MM_update" value="FormEditarFrec" />
    </form>
 
<p>&nbsp;</p>
<p>&nbsp;</p>
 
<?php
	if(@$_POST['botonEliminar']) {
 
		foreach($_POST['Borrar'] as $intContador) {
 
			mysql_query('DELETE FROM tblfrecuentes WHERE intContador = '.$intContador);
 
		}
 
		echo "<META HTTP-EQUIV='refresh' CONTENT='0; URL=editar-preguntas.php'>";
 
	}
?>
 
<?php
	if((@$_POST['botonActualizar']) && ($_POST["MM_update"] == "FormEditarFrec")){
 
			foreach($_POST['nroReg'] as $intContador) {
 
				$query = sprintf("UPDATE tblfrecuentes SET intEstado=%s, strRespuesta=%s, strTexto=%s WHERE intContador=%s",
						   GetSQLValueString($_POST['estado'], "int"),
						   GetSQLValueString(utf8_decode($_POST['respuesta']), "text"),
						   GetSQLValueString(utf8_decode($_POST['pregunta']), "text"),
						   $intContador);
 
				$Res = mysql_query($query, $conexionespeciales) or die(mysql_error());
			}
 
		echo "<META HTTP-EQUIV='refresh' CONTENT='0; URL=editar-preguntas.php'>";
 
	}
?>
 
<?php
mysql_free_result($EditarFrecuentes);
?>



NOTA: Adjunte el php en el zip por si no se entiende.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de xve
Val: 3.943
Oro
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Modificar varios registros a la vez

Publicado por xve (6935 intervenciones) el 22/12/2014 08:08:36
Hola John, hasta donde yo se, no es posible modificar varios registros con diferentes valores cada uno en un solo UPDATE... tenderas que hacer un update para cada registro que sea diferente.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Modificar varios registros a la vez

Publicado por John (4 intervenciones) el 22/12/2014 21:41:18
Tengo entendido que es posible creando arrays, e podido avanzar un poco pero aún no logro hacerlo funcionar, si lo logro avisaré de cualquier manera
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Modificar varios registros a la vez

Publicado por John (4 intervenciones) el 23/12/2014 01:34:10
Dejo el código, finalmente pude hacerlo, para todos los que lo necesiten:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php require_once('Connections/conexionespeciales.php'); ?>
<?php
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;
}
}
 
mysql_select_db($database_conexionespeciales, $conexionespeciales);
$query_EditarFrecuentes = "SELECT intContador, tblfrecuentes.strTexto, tblfrecuentes.strRespuesta, tblfrecuentes.intEstado FROM tblfrecuentes ORDER BY tblfrecuentes.fchFecha DESC";
$EditarFrecuentes = mysql_query($query_EditarFrecuentes, $conexionespeciales) or die(mysql_error());
$row_EditarFrecuentes = mysql_fetch_assoc($EditarFrecuentes);
$totalRows_EditarFrecuentes = mysql_num_rows($EditarFrecuentes);
 
$editFormAction = $_SERVER['PHP_SELF'];
	if (isset($_SERVER['QUERY_STRING'])) {
  		$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
	}
 
?>
 <form action="<?php echo $editFormAction; ?>" method="post" name="FormEditarFrec" id="FormEditarFrec">
  <table align="center">
<?php do {
	$id = $row_EditarFrecuentes["intContador"];
echo '
  <tr>	<input type="hidden" name="id_list[]" value="' . $id . '">
		<td><input name="nroReg" value="' . $id . '" size="1" readonly="readonly" /></td>
        <td><input type="text" name="pregunta[' . $id . ']?>]" value="'.htmlentities(utf8_encode($row_EditarFrecuentes["strTexto"])).'" size="32"/></td>
		<td><input type="text" name="respuesta[' . $id . ']?>]" value="'.htmlentities(utf8_encode($row_EditarFrecuentes["strRespuesta"])).'" size="32" /></td>
        <td><input type="text" name="estado[' . $id . ']" value="'.htmlentities(utf8_encode($row_EditarFrecuentes["intEstado"])).'" size="2" />
        </td>
        <td><input name="Borrar[]" type="checkbox" value="' . $id . '" /></td>
   </tr>
 ';
 } while ($row_EditarFrecuentes = mysql_fetch_assoc($EditarFrecuentes));
 ?>
  </table>
 
    <br /><div align="center">
    <input class="boton" name="botonActualizar" type="submit" value="Actualizar registro/s" />
     <input class="boton" name="botonEliminar" type="submit" value="Borrar registro/s" /></div>
    <input type="hidden" name="MM_update" value="FormEditarFrec" />
    </form>
 
<p>&nbsp;</p>
<p>&nbsp;</p>
 
<?php
	if(@$_POST['botonEliminar']) {
 
		foreach($_POST['Borrar'] as $intContador) {
 
			mysql_query('DELETE FROM tblfrecuentes WHERE intContador = '.$intContador);
 
		}
 
		echo "<META HTTP-EQUIV='refresh' CONTENT='0; URL=editar-preguntas.php'>";
 
	}
?>
 
<?php
	if((@$_POST['botonActualizar']) && ($_POST["MM_update"] == "FormEditarFrec")){
 
			foreach($_POST['id_list'] as $id) {
 
				$state = utf8_decode($_POST["estado"][$id]);
				$question = utf8_decode($_POST["pregunta"][$id]);
				$answer = utf8_decode($_POST["respuesta"][$id]);
 
				$query = sprintf("UPDATE tblfrecuentes SET intEstado='$state', strRespuesta='$answer', strTexto='$question' WHERE intContador=$id");
 
				$Res = mysql_query($query, $conexionespeciales) or die(mysql_error());
			}
 
		echo "<META HTTP-EQUIV='refresh' CONTENT='0; URL=editar-preguntas.php'>";
 
	}
?>
<?php
mysql_free_result($EditarFrecuentes);
?>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de xve
Val: 3.943
Oro
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Modificar varios registros a la vez

Publicado por xve (6935 intervenciones) el 23/12/2014 08:57:58
Hola John, gracias por compartirlo, pero veo que haces de uno en uno en un bucle, no? Entiendo que como lo has realizado es la manera estándar, tal y como lo hacemos todos.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Modificar varios registros a la vez

Publicado por John (4 intervenciones) el 23/12/2014 22:35:22
Sí, se guardan los valores en arrays y se van actualizando los datos de a uno, pero se modifican todos los datos del formulario simplemente clickeando una única vez.
Muchas gracias de todas maneras por contestar!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar