PHP - Ayuda por favor en un abm!

 
Vista:
sin imagen de perfil

Ayuda por favor en un abm!

Publicado por Dio (15 intervenciones) el 16/12/2014 02:56:22
Tengo un problema con un abm, me anda todo menos la parte de modificación. La query está bien, no logro encontrar el problema, miro mil veces todo y no veo porqué no anda. La ventana de Jquery sale, me carga bien todos los datos pero cuando le doy guardar no se guarda (la ventana se cierra como si se hubiese guardado, pero la base de datos no hizo el UPDATE)
Aca les dejo la class donde está el método updatePais, el index donde se carga (tiene un swich case), las funciones en jquery y el template de la ventana de modificacion.
Si alguien descubre donde está el error se lo agradecería infinitamente!

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
109
110
class Pais
{
	var $codigo;
	var $nombre;
	var $poblacion;
	var $pbi;
	Var $relevamiento;
	var $region;
 
    public static function getPaises()
		{
			$obj_pais=new sQuery();
			$obj_pais->executeQuery("SELECT r.Nombre as 'Region'
									     , p.Nombre as 'Pais'
									     , p.poblacion as 'Poblacion'
									     , p.PBI as 'PBI'
									     , p.FechaRelevamiento 'Relevamiento'
									     , p.codigo as 'Codigo'
									  FROM region r
									 INNER JOIN pais p
									    ON r.id = p.RegionId
									 ORDER BY p.regionId asc, p.nombre asc");
 
			return $obj_pais->fetchAll();
		}
 
	function Pais($cod=null) // declara el constructor, si trae el codigo de pais lo busca , si no, trae todos los paises
	{
		if ($cod!=null)
		{
			$obj_pais=new sQuery();
			$result=$obj_pais->executeQuery("SELECT r.Nombre as 'Region'
											     , p.Nombre as 'Pais'
											     , p.poblacion as 'Poblacion'
											     , p.PBI as 'PBI'
											     , p.FechaRelevamiento 'Relevamiento'
											     , p.codigo as 'Codigo'
											  FROM region r
											 INNER JOIN pais p
											    ON r.id = p.RegionId
											 WHERE Codigo='".$cod."'
											 ORDER BY p.regionId asc, p.nombre asc");
			$row=mysqli_fetch_array($result);
			$this->codigo=$row['Codigo'];
			$this->nombre=$row['Pais'];
			$this->poblacion=$row['Poblacion'];
			$this->pbi=$row['PBI'];
			$this->relevamiento=$row['Relevamiento'];
			$this->region=$row['Region'];
		}
	}
 
	// metodos que devuelven valores
	function getCodigo()
	 { return $this->codigo;}
	function getNombre()
	 { return $this->nombre;}
	function getPoblacion()
	 { return $this->poblacion;}
	function getPbi()
	 { return $this->pbi;}
	function getRelevamiento()
	 { return $this->relevamiento;}
	 function getRegion()
	 { return $this->region;}
 
		// metodos que setean los valores
	function setCodigo($val)
	 { $this->codigo=$val;}
	function setNombre($val)
	 { $this->nombre=$val;}
	function setPoblacion($val)
	 {  $this->poblacion=$val;}
	function setPbi($val)
	 {  $this->pbi=$val;}
	function setRelevamiento($val)
	 {  $this->relevamiento=$val;}
	 function setRegion($val)
	 {  $this->region=$val;}
 
    function save()
    {
        if($this->codigo)
        {$this->updatepais();}
    }
	private function updatePais()	// actualiza el pais cargado en los atributos
	{
			$obj_pais=new sQuery();
			$query="update pais set nombre='".$this->nombre."', poblacion='".$this->poblacion."', pbi='".$this->pbi."', fechaRelevamiento='".$this->relevamiento."' WHERE codigo='".$this->codigo."'";
			$obj_pais->executeQuery($query); // ejecuta la consulta para traer al pais 
			return $obj_pais->getAffect(); // retorna todos los registros afectados
 
	}
 
	function delete()	// elimina el pais
	{
			$obj_pais=new sQuery();
			$query="delete from pais where codigo='".$this->codigo."'";
			$obj_pais->executeQuery($query); // ejecuta la consulta para  borrar el pais
			return $obj_pais->getAffect(); // retorna todos los registros afectados
	}
}
function cleanString($string)
{
    $string=trim($string);
    $string=mysqli_escape_string($string);
	$string=htmlspecialchars($string);
 
    return $string;
}

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
<?php
include_once ("clase.php");// incluyo las clases a ser usadas
$action='index';
if(isset($_POST['action']))
{$action=$_POST['action'];}
 
 
$view= new stdClass(); // creo una clase standard para contener la vista
$view->disableLayout=false;// marca si usa o no el layout , si no lo usa imprime directamente el template
 
// para no utilizar un framework y simplificar las cosas uso este switch, la idea
// es que puedan apreciar facilmente cuales son las operaciones que se realizan
switch ($action)
{
    case 'index':
        $view->paises=Pais::getpaises(); // tree todos los paises
        $view->contentTemplate="templates/paisesGrid.php"; // seteo el template que se va a mostrar
        break;
    case 'refreshGrid':
        $view->disableLayout=true; // no usa el layout
        $view->paises=Pais::getpaises();
        $view->contentTemplate="templates/paisesGrid.php"; // seteo el template que se va a mostrar
        break;
    case 'saveCountry':
        // limpio todos los valores antes de guardarlos por las dudas venga algo raro
        $codigo=$_POST['Country'];
        $nombre=cleanString($_POST['nombre']);
        $poblacion=cleanString($_POST['poblacion']);
        $pbi=cleanString($_POST['pbi']);
        $relevamiento=cleanString($_POST['relevamiento']);
        $pais=new Pais($codigo);
        $pais->setCodigo($codigo);
        $pais->setNombre($nombre);
        $pais->setPoblacion($poblacion);
        $pais->setPbi($pbi);
        $pais->setRelevamiento($relevamiento);
        $pais->save();
        break;
    case 'editCountry':
        $editCodigo=$_POST['codigo'];
        $view->label='Editar pais';
        $view->Country=new pais($editCodigo);
        $view->disableLayout=true;
        $view->contentTemplate="templates/CountryForm.php"; // seteo el template que se va a mostrar
        break;
    case 'deleteCountry':
        $codigo=$_POST['codigo'];
        $Country=new pais($codigo);
        $Country->delete();
        die; // no quiero mostrar nada cuando borra , solo devuelve el control.
        break;
    default :
}
 
// si esta deshabilitado el layout solo imprime el template
if ($view->disableLayout==true)
{include_once ($view->contentTemplate);}
else
{include_once ('templates/layout.php');} // el layout incluye el template adentro

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
$(document).ready(function(){ //cuando el html fue cargado iniciar
 
    //añado la posibilidad de editar al presionar sobre edit
    $('.edit').live('click',function(){
        //this = es el elemento sobre el que se hizo click en este caso el link
        //obtengo el codigo que guardamos en data-id
        var codigo=$(this).attr('data-id');
        //preparo los parametros
        params={};
        params.codigo=codigo;
        params.action="editCountry";
        $('#popupbox').load('index.php', params,function(){
            $('#block').show();
            $('#popupbox').show();
        })
 
    })
 
    $('.delete').live('click',function(){
        //obtengo el id que guardamos en data-id
        var codigo=$(this).attr('data-id');
        //preparo los parametros
        params={};
        params.codigo=codigo;
        params.action="deleteCountry";
        $('#popupbox').load('index.php', params,function(){
            $('#content').load('index.php',{action:"refreshGrid"});
        })
 
    })
 
    $('#Country').live('submit',function(){
            var params={};
            params.action='saveCountry';
            params.codigo=$('#codigo').val();
            params.nombre=$('#nombre').val();
            params.poblacion=$('#poblacion').val();
            params.pbi=$('#pbi').val();
            params.relevamiento=$('#relevamiento').val();
            $.post('index.php',params,function(){
                $('#block').hide();
                $('#popupbox').hide();
                $('#content').load('index.php',{action:"refreshGrid"});
            })
            return false;
        })
// boton cancelar, uso live en lugar de bind para que tome cualquier boton nuevo que pueda aparecer nuevo que pueda aparecer
    $('#cancel').live('click',function(){
        $('#block').hide();
        $('#popupbox').hide();
    })
})
 
NS={};

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
<table>
    <thead>
        <tr class="enunciados">
            <th>Region</th>
            <th>País</th>
            <th>Población</th>
            <th>PBI</th>
            <th>PBI/cápita</th>
            <th>Relevamiento</th>
            <th>Modificar</th>
            <th>Eliminar</th>
        </tr>
    </thead>
    <tbody>
        <?php
        foreach ($view->paises as $pais):  // uso la otra sintaxis de php para templates ?>
            <tr>
                <td class="region"><?php echo $pais['Region'];?></td>
                <td><?php echo $pais['Pais'];?></td>
                <td><?php echo $pais['Poblacion'];?></td>
                <td><?php echo $pais['PBI'];?></td>
                <td class="pbixcap"><?php if($pais['PBI']&&$pais['Poblacion']!=null){echo $pais['PBI']/$pais['Poblacion'];}else{echo "NHI";}; ?></td>
                <td><?php echo $pais['Relevamiento'];?></td>
                <td><a class="edit"   href="javascript:void(0);" data-id="<?php echo $pais['Codigo'];?>"><img src="imgs/modificar.png"></a></td>
                <td><a class="delete" href="javascript:void(0);" data-id="<?php echo $pais['Codigo'];?>"><img src="imgs/borrar.png"></a></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>
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
sin imagen de perfil

Ayuda por favor en un abm!

Publicado por Dio (15 intervenciones) el 16/12/2014 07:02:29
Me confundí, este es el template del formulario
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
<h2><?php echo $view->label ?></h2>
<form name ="Country" id="Country" method="POST" action="index.php">
    <table>
        <input type="hidden" name="codigo" id="codigo" value="<?php echo $view->Country->getCodigo() ?>">
        <tr>
            <td>Pais</td>
            <td><input type="text" name="nombre" id="nombre" value = "<?php echo $view->Country->getNombre() ?>"></td>
        </tr>
        <tr>
            <td>Poblacion</td>
            <td><input type="text" name="poblacion" id="poblacion"value = "<?php echo $view->Country->getPoblacion() ?>"></td>
        </tr>
        <tr>
            <td>PBI</td>
            <td><input type="text" name="pbi" id="pbi" value = "<?php echo $view->Country->getPbi() ?>"></td>
        </tr>
        <tr>
            <td>Fecha relevamiento</td>
            <td><input type="text" name="relevamiento" id="relevamiento" value = "<?php echo $view->Country->getRelevamiento() ?>">(yyyy-mm-dd)</td>
        </tr>
        <tr>
            <td><input id="cancel" type="button" value ="Cancelar" /></td>
            <td><input id="submit" type="submit" name="submit" value ="Guardar" /></td>
        </tr>
    </table>
</form>
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