PHP - Insert y update datos mysql

 
Vista:

Insert y update datos mysql

Publicado por racingman (14 intervenciones) el 22/08/2012 00:15:09
Buenas noches,

He implementado el siguiente ejemplo, pero realizando unos cuantos cambios:

http://www.ribosomatic.com/articulos/tutorial-aplicacion-web-con-jquery-php-mysql-mantenimiento-de-datos/

Antes de mostrar los datos de todos los clientes, tengo creado una <select> en la cual selecciono el tipo de cliente y y despues de realizar la seleccion me salen los correspondientes clientes al tipo seleccionado.

Hasta aqui todo bien, luego por ejemplo voy a añadir un nuevo registro el cual se guarda correctamente, pero luego al volver al listado me borra la seleccion de la <select>, con lo cual pierdo la seleccion anterior.

Si le quito la <select> realiza todo correctamente. Guarda bien en la base de datos y despues vuelve al listado de los clientes actualizandolos. Pero me hace falta que funciona tal cual esta el ejemplo pero con la <select>

Alguna solucion?

Muchas gracias
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

Insert y update datos mysql

Publicado por xve (6935 intervenciones) el 22/08/2012 10:49:50
Hola, nos puedes mostrar tu código?? es para ver por donde puedes tener el problema...
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

Insert y update datos mysql

Publicado por racingman (14 intervenciones) el 23/08/2012 11:15:39
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
include('../header.php');
?>
<script src="js/jquery/jquery-latest.js" type="text/javascript"></script>
<script src="js/jquery/jquery.functions.js" type="text/javascript"></script>
<div>
    <div id="formulario">
	<?php include('selecarrera.php') ?>
    </div>
    <div id="tabla">
    <?php include('consulta.php') ?>
    </div>
</div>
<?php include('../footer.php'); ?>


consulta.php
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
<script type="text/javascript">
$(document).ready(function(){
	// mostrar formulario de actualizar datos
	$("table tr .modi a").click(function(){
		$('#tabla').hide();
		$("#formulario").show();
		$.ajax({
			url: this.href,
			type: "GET",
			success: function(datos){
				$("#formulario").html(datos);
			}
		});
		return false;
	});
 
	// llamar a formulario nuevo
	$("#nuevo a").click(function(){
		$("#formulario").show();
		$("#tabla").hide();
		$.ajax({
			type: "GET",
			url: 'nuevo.php',
			success: function(datos){
				$("#formulario").html(datos);
			}
		});
		return false;
	});
});
</script>
	<p>
	<?php if($_POST["miSelect"]!=0) {
	require('../clases/cliente.class.php');
	$objCliente=new Cliente;
	//$consulta=$objCliente->mostrar_clientes();
	$consulta = $objCliente->mostrar_clientes($IDCarrera);
	?>
	<table width="950" id="mytable" cellspacing="0">
   		<tr>
   			<th scope="col" width="20"></th>
    		<th scope="col" width="200">CONCURSANTE</th>
    		<th scope="col" width="200">PILOTO</th>
    		<th scope="col" width="200">COPILOTO</th>
            <th scope="col" width="200">VEHICULO</th>
			<th scope="col" width="20">JUNIOR</th>
			<th scope="col" width="20">CLASE</th>
			<th scope="col" width="20">GRUPO</th>
			<th scope="col" width="20">COPA</th>
            <th scope="col" class="nobgRi" width="20"><span id="nuevo"><a href="nuevo.php"><img src="../images/add.png" alt="Agregar dato" /></a></span></th>
            <th scope="col" class="nobgLeRi" width="20"></th>
        </tr>
<?php while( $cliente = mysql_fetch_array($consulta) ){ ?>
		  <tr id="fila-<?php echo $cliente['IDParticipanteT02'] ?>">
			  <th scope="row" class="spec"><?php echo $cliente['DorsalT02'] ?></td>
			  <td><?php echo $cliente['NombreClubT05'] ?></td>
			  <td><?php echo $cliente['PilotoT02'] ?></td>
			  <td><?php echo $cliente['CopilotoT02'] ?></td>
			  <td><?php echo $cliente['VehiculoT02'] ?></td>
			  <td align="center">
				<?php if ($resEmp6['JuniorT02']==0) {?>
					<?php echo ""; ?>
				<?php }else{ ?>
					<?php echo "Jr."; ?>
				<?php } ?>
			  </td>
			  <td align="center"><?php echo $cliente['NombreT08'] ?></td>
			  <td align="center"><?php echo $cliente['NombreT07'] ?></td>
			  <td align="center"><?php echo $cliente['NombreT06'] ?></td>
			  <td><span class="modi"><a href="actualizar.php?id=<?php echo $cliente['id'] ?>"><img src="../images/database_edit.png" title="Editar" alt="Editar" /></a></span></td>
			  <td><span class="dele"><a onClick="EliminarDato(<?php echo $cliente['id'] ?>); return false" href="eliminar.php?id=<?php echo $cliente['id'] ?>"><img src="../images/delete.png" title="Eliminar" alt="Eliminar" /></a></span></td>
		  </tr>
	<?php
	}
}
?>
</table>
<p>


nuevo.php
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
<?php
include("../../conexion.php");
$query2 = "SELECT * FROM T05Clubes ORDER BY NombreClubT05 ASC";
$query3 = "SELECT * FROM T06Copas ORDER BY NombreT06 ASC";
$query4 = "SELECT * FROM T07Grupo ORDER BY NombreT07 ASC";
$query5 = "SELECT * FROM T08Clase ORDER BY NombreT08 ASC";
$queEmp2 = mysql_query($query2, $conexion);
$queEmp3 = mysql_query($query3, $conexion);
$queEmp4 = mysql_query($query4, $conexion);
$queEmp5 = mysql_query($query5, $conexion);
 
 
if(isset($_POST['submit'])){
	require('../clases/cliente.class.php');
 
	$Dorsal = htmlspecialchars(trim($_POST['dorsal']));
	$IDClub = htmlspecialchars(trim($_POST['miConcursante']));
	$Piloto = htmlspecialchars(trim($_POST['piloto']));
	$Copiloto = htmlspecialchars(trim($_POST['copiloto']));
	$Vehiculo = htmlspecialchars(trim($_POST['vehiculo']));
	$IDGrupo = htmlspecialchars(trim($_POST['miGrupo']));
	$IDClase = htmlspecialchars(trim($_POST['miClase']));
	$IDCopa = htmlspecialchars(trim($_POST['miCopa']));
	$Junior = htmlspecialchars(trim($_POST['junior']));
 
	$objCliente=new Cliente;
	if ( $objCliente->insertar(array($Dorsal,$IDClub,$Piloto,$Copiloto,$Vehiculo,$IDGrupo,$IDClase,$IDCopa,$Junior)) == true){
		echo 'Datos guardados';
	}else{
		echo 'Se produjo un error. Intente nuevamente';
	}
}else{
?>
<form id="frmClienteNuevo" name="frmClienteNuevo" method="post" action="nuevo.php" onsubmit="GrabarDatos(); return false">
<table border="0">
	<tr>
		<td class="no">Dorsal:<br />
			<input  name="dorsal" type="text" size="5" class="required"></td>
		<td class="no">Concursante:<br />
			<select name="miConcursante">
				<option value="">Concursante</option>
				<?php
					while ($resEmp2 = mysql_fetch_array($queEmp2)){
							echo '<option value="'.$resEmp2['IDClubT05'].'">'.$resEmp2['NombreClubT05'].'</option>';
					}
				?>
			</select></td>
		<td class="no">Piloto:<br />
			<input name="piloto" type="text" size="20" class="required"></td>
      	<td class="no">Copiloto:<br />
			<input name="copiloto" type="text" size="20" class="required"></td>
		<td class="no">Veh&iacute;culo:<br />
			<input name="vehiculo" type="text" size="20" class="required"></td>
		<td class="no">Junior:<br />
			<select name="junior" type="text">
          		<option value="1">Si</option>
          		<option value="0" selected="selected">No</option>
            </select></td>
		<td class="no">Clase:<br />
			<select name="miClase">
				<option value="">Clase</option>
				<?php
					while ($resEmp5 = mysql_fetch_array($queEmp5)){
							echo '<option value="'.$resEmp5['IDClaseT08'].'">'.$resEmp5['NombreT08'].'</option>';
					}
				?>
			</select></td>
		<td class="no">Grupo:<br />
			<select name="miGrupo">
				<option value="">Grupo</option>
				<?php
					while ($resEmp4 = mysql_fetch_array($queEmp4)){
							echo '<option value="'.$resEmp4['IDGrupoT07'].'">'.$resEmp4['NombreT07'].'</option>';
					}
				?>
			</select></td>
		<td class="no">Copa:<br />
			<select name="miCopa">
				<option value="">Copa</option>
				<?php
					while ($resEmp3 = mysql_fetch_array($queEmp3)){
							echo '<option value="'.$resEmp3['IDCCopaT06'].'">'.$resEmp3['NombreT06'].'</option>';
					}
				?>
			</select>
		</tr>
	</table>
    <input type="submit" name="submit" id="button" value="Enviar" />
    <label></label>
    <input type="button" class="cancelar" name="cancelar" id="cancelar" value="Cancelar" onclick="Cancelar()" />
  </p>
</form>
<?php
}
?>


j.query.functions.js
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
function ActualizarDatos(){
		var cliente_id = $('#cliente_id').attr('value');
		var nombres = $('#nombres').attr('value');
		var ciudad = $('#ciudad').attr('value');
		var alternativas = $("input[@name='alternativas']:checked").attr("value");
		var telefono = $("#telefono").attr("value");
		var fecha_nacimiento = $("#fecha_nacimiento").attr("value");
 
		$.ajax({
			url: 'actualizar.php',
			type: "POST",
			data: "submit=&nombres="+nombres+"&ciudad="+ciudad+"&alternativas="+alternativas+"&telefono="+telefono+"&fecha_nacimiento="+fecha_nacimiento+"&cliente_id="+cliente_id,
			success: function(datos){
				alert(datos);
				ConsultaDatos();
				$("#formulario").hide();
				$("#tabla").show();
			}
		});
		return false;
	}
 
	function ConsultaDatos(){
		$.ajax({
			url: 'index.php',
			cache: false,
			type: "GET",
			success: function(datos){
				$("#tabla").html(datos);
			}
		});
	}
 
	function EliminarDato(cliente_id){
		var msg = confirm("Desea eliminar este dato?")
		if ( msg ) {
			$.ajax({
				url: 'eliminar.php',
				type: "GET",
				data: "id="+cliente_id,
				success: function(datos){
					alert(datos);
					$("#fila-"+cliente_id).remove();
				}
			});
		}
		return false;
	}
 
	function GrabarDatos(){
		var Dorsal = $('#Dorsal').attr('value');
		var IDClub = $('#IDClub').attr('value');
		var Piloto = $('#Piloto').attr('value');
		var Copiloto = $('#Copiloto').attr('value');
		var Vehiculo = $('#Vehiculo').attr('value');
		var IDGrupo = $('#IDGrupo').attr('value');
		var IDClase = $('#IDClase').attr('value');
		var IDCopa = $('#IDCopa').attr('value');
		var Junior = $('#Junior').attr('value');
 
		$.ajax({
			url: 'nuevo.php',
			type: "POST",
			data: "submit=&Dorsal="+Dorsal+"&IDClub="+IDClub+"&Piloto="+Piloto+"&Copiloto="+Copiloto+"&Vehiculo="+Vehiculo+"&IDGrupo="+IDGrupo+"&IDClase="+IDClase+"&IDCopa="+IDCopa+"&Junior="+Junior,
			success: function(datos){
				ConsultaDatos();
				alert(datos);
				$("#formulario").hide();
				$("#tabla").show();
			}
		});
		return false;
	}
 
	function Cancelar(){
		$("#formulario").hide();
		$("#tabla").show();
		return false;
	}
 
	// funciones del calendario
	function update_calendar(){
		var month = $('#calendar_mes').attr('value');
		var year = $('#calendar_anio').attr('value');
 
		var valores='month='+month+'&year='+year;
 
		$.ajax({
			url: 'calendario.php',
			type: "GET",
			data: valores,
			success: function(datos){
				$("#calendario_dias").html(datos);
			}
		});
	}
 
	function set_date(date){
		$('#fecha_nacimiento').attr('value',date);
		show_calendar();
	}
 
	function show_calendar(){
		$('#calendario').toggle();
	}


Al hacer click para agregar un registro nuevo y luego si en el formulario le doy a cancelar vuelve correctamente a donde yo quiero, pero si doy de alta un registro nuevo es cuando tengo el problema.

Muchas gracias
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

Insert y update datos mysql

Publicado por Ignacio Esviza (16 intervenciones) el 23/08/2012 11:54:37
Hola.

Lo que tenés que lograr es que siempre que se dibuje la pantalla que contiene el SELECT, éste sepa cuál es la opción que el usuario había elegido alguna vez. Eso independientemente de por dónde llegaste a la pantalla, no debería importar si agregaste o no un cliente o de donde sea: el SELECT debe "recordar" cuál es el valor que el usuario eligió antes.

Una alternativa (hay otras) es hacerlo con variables de sesión.

1. Cuando requieras dibujar el SELECT recuperás el valor antiguamente seleccionado por el usuario (si hay alguno):

session_start(); // -- esta línea debería hacie el inicio de la ejecución.
$valorSeleccionado = isset( $_SESSION['seleccion'] ) ? $_SESSION['seleccion'] : 0;

2. Toda vez que proceses un cambio en la selección del usuario debés guardar:

session_start(); // -- esta línea debería hacie el inicio de la ejecución.
$_SESSION['seleccion'] = $valorSeleccionado;

De esa manera no importa de dónde vengas o hacia dónde vayas, siempre que el usuario modifique el valor seleccionado del SELECT debés guardarlo en una variable de sesión así al volver a la página lo recuerda.

Saludos
Ignacio Esviza
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