PHP - Cambiar GET por POST

 
Vista:
sin imagen de perfil

Cambiar GET por POST

Publicado por Alberto (11 intervenciones) el 27/04/2017 23:30:13
Tengo un aplicacion web que da base a una BBDD en la cual puede modificar de cualquier manera las tablas o ingresar datos.
El problema es que esto lo hace por GET, todos sabemos el problema que esto acarrea, e decidido pasarlo por POST para evitar estos dolores de cabeza pero me encuentro con otros.
Modifique todos los GET por POST y aun asi no funciona, la sentencia sql que muestra la tabla la deja completamente en blanco como si no hubiera registros, pero si intento ingresar un registro lo hace perfectamente, pero claro no lo visualiza pero si accedo a phpmyadmin puedo ver que este se a ingresado correctamente.
Entonces el kit de la cuestion es, como cambio los GET por POST y que funcione tal y como esta ahora evitando que pasen por la URL como necesito en el final del index.php

Os inserto los 3 archivos originales con GET que utilizo .

Index .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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
require_once 'alumno.entidad.php';
require_once 'alumno.model.php';
 
// Logica
$alm = new Categoria();
$model = new CategoriaModel();
 
if (isset($_REQUEST['action'])) {
    switch ($_REQUEST['action']) {
        case 'actualizar':
 
 
 
            // Recupero el id del campo hidden
 
            $alm->__SET('acronimo', $_REQUEST['acronimo']);
 
            $alm->__SET('categoria', $_REQUEST['categoria']);
 
 
 
            $update_results = $model->Actualizar($alm, $_POST['id']);
 
            header('Location: index.php');
 
            break;
 
        case 'registrar':
            $alm->__SET('acronimo', $_REQUEST['acronimo']);
            $alm->__SET('categoria', $_REQUEST['categoria']);
 
            $model->Registrar($alm);
            header('Location: index.php');
            break;
 
        case 'eliminar':
            $model->Eliminar($_REQUEST['acronimo']);
            header('Location: index.php');
            break;
 
        case 'editar':
            // Recupero los datos por el id
            // $obj_categoria es un objeto del tipo Categoria
            $obj_categoria = $model->Obtener($_REQUEST['id']);
            break;
        default:
            // MENSAJE 404 PARA CUANDO LA ACCION NO ES VALIDA
            header('HTTP/1.0: 404 Not Found');
            die('<h1>404 Page Not Found</h1>');
    }
}
?>
 
<!DOCTYPE html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css">
    </head>
    <body style="padding:15px;">
 
        <div class="pure-g">
            <div class="pure-u-1-12">
 
                <form action="?action=<?php echo isset($obj_categoria) ? 'actualizar' : 'registrar'; ?>" method="POST" class="pure-form pure-form-stacked" style="margin-bottom:30px;">
                    <input type="hidden" name="id" value="<?php echo isset($obj_categoria) ? $obj_categoria->__GET('acronimo') : ''; ?>" />
 
                    <table style="width:500px;">
                        <tr>
                            <th style="text-align:left;">Acronimo</th>
                            <td><input type="text" name="acronimo"  value="<?php echo isset($obj_categoria) ? $obj_categoria->__GET('acronimo') : ''; ?>" style="width:100%;" required /></td>
                        </tr>
                        <tr>
                            <th style="text-align:left;">Categoria</th>
                            <td><input type="text" name="categoria"  value="<?php echo isset($obj_categoria) ? $obj_categoria->__GET('categoria') : ''; ?>" style="width:100%;" required/></td>
                            <td colspan="2">
                                <button type="submit" class="pure-button pure-button-primary">Guardar</button>
                            </td>
                        </tr>
                    </table>
                </form>
 
                <table class="pure-table pure-table-horizontal">
                    <thead>
                        <tr>
                            <th style="text-align:left;">Acronimo</th>
                            <th style="text-align:left;">Categoria</th>
                            <th style="text-align:left;">Edición</th>
                            <th style="text-align:left;">Eliminar</th>
 
                        </tr>
                    </thead>
<?php foreach ($model->Listar() as $r): ?>
                        <tr>
                            <td><?php echo $r->__GET('acronimo'); ?></td>
                            <td><?php echo $r->__GET('categoria'); ?></td>
 
                            <td>
    <a href="?action=editar&id=<?php echo urlencode($r->acronimo); ?>"><img src="icon_editthis.png" width="30px" height="30px"/></a>
</td>
<td>
    <a href="?action=eliminar&acronimo=<?php echo urlencode($r->acronimo); ?>"><img src="delete.png" width="30px" height="30px"/></a>
</td>
                        </tr>
<?php endforeach; ?>
                </table>
 
            </div>
        </div>
 
    </body>
</html>

alumno.model.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
 
class CategoriaModel {
 
    private $pdo;
 
    public function __CONSTRUCT() {
        try {
            $this->pdo = new PDO('mysql:host=localhost;dbname=deimos1;charset=UTF8', 'root', '');
            $this->pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
            $this->pdo->exec("SET NAMES 'utf8';");
        } catch (Exception $e) {
            die($e->getMessage());
        }
    }
 
    public function Listar() {
        try {
            $result = array();
 
            $stm = $this->pdo->prepare("SELECT * FROM categoria");
            $stm->execute();
 
            foreach ($stm->fetchAll(PDO::FETCH_OBJ) as $r) {
                $alm = new Categoria();
 
                $alm->__SET('acronimo', $r->acronimo);
                $alm->__SET('categoria', $r->categoria);
 
                $result[] = $alm;
            }
 
            return $result;
        } catch (Exception $e) {
            die($e->getMessage());
        }
    }
 
    public function Obtener($acronimo) {
        try {
            $stm = $this->pdo->prepare('SELECT * FROM categoria WHERE acronimo = ?');
            $stm->execute(array($acronimo));
            $r = $stm->fetch(PDO::FETCH_ASSOC);
 
            $alm = new Categoria();
 
            $alm->__SET('acronimo', $r["acronimo"]);
            $alm->__SET('categoria', $r["categoria"]);
 
            return $alm;
        } catch (Exception $e) {
            die($e->getMessage());
        }
    }
 
    public function Eliminar($acronimo) {
        try {
            $stm = $this->pdo
                    ->prepare("DELETE FROM categoria WHERE acronimo = ?");
 
            $stm->execute(array($acronimo));
        } catch (Exception $e) {
            die($e->getMessage());
        }
    }
 
    // ##############################################################################################
    // CAMBIOS REALIZADOS
    // - USO DE PARAMETROS NOMBRADOS EN EN METODO .execute()
    // ##############################################################################################		
    public function Actualizar(Categoria $data, $acronimo_viejo) {
 
        try {
 
            $sql = "UPDATE categoria SET categoria =:categoria, acronimo =:acronimo WHERE acronimo=:acronimo_viejo";
 
 
 
            return $this->pdo->prepare($sql)
                            ->execute(
                                    array(
                                        ':acronimo_viejo' => $acronimo_viejo,
                                        ':acronimo' => $data->__GET('acronimo'),
                                        ':categoria' => $data->__GET('categoria')
                                    )
            );
        } catch (Exception $e) {
 
            die($e->getMessage());
        }
    }
 
    // ##############################################################################################
 
    public function Registrar(Categoria $data) {
        try {
            $sql = "INSERT INTO categoria (acronimo,categoria)
		        VALUES (?, ?)";
 
            $this->pdo->prepare($sql)
                    ->execute(
                            array(
                                $data->__GET('acronimo'),
                                $data->__GET('categoria')
                            )
            );
        } catch (Exception $e) {
            die($e->getMessage());
        }
    }
 
}

alumno.entidad.php

<?php
1
2
3
4
5
6
7
8
class Categoria
{
	private $acronimo;
	private $categoria;
 
        public function __GET($k){ return $this->$k; }
	public function __SET($k, $v){ return $this->$k = $v; }
}
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

Cambiar GET por POST

Publicado por xve (6935 intervenciones) el 28/04/2017 08:48:15
Hola Alberto, al hacer esto:
1
<form action="?action=<?php echo isset($obj_categoria) ? 'actualizar' : 'registrar'; ?>" method="POST" ...
lo que estas haciendo, es pasando la variable action por GET y los valores del formulario por POST

Puede ser este 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
sin imagen de perfil

Cambiar GET por POST

Publicado por Alberto (11 intervenciones) el 28/04/2017 10:52:41
Exacto, entonces tenog que pasar las variables por la URL y lo que quieor es evitar pasar las variables por la URL e intentado modificar algunas cosas y consigo que funcione por POST pero no consigo ni editar ni eliminar registros esos botones se me quedan obsoletos
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