Nueva pregunta

Pregunta:

Fecha: 27-04-2017 05:53:04 (En Español)

Cambiar variables GET por POST[No resuelta]

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

<?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.entidad.php

<?php
class Categoria
{
	private $acronimo;
	private $categoria;

	public function __POST($k){ return $this->$k; }
        public function __GET($k){ return $this->$k; }
	public function __SET($k, $v){ return $this->$k = $v; }
}


alumno.model.php

<?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());
        }
    }

}


Muchisimas gracias y un placer haber encontrado este foro
Etiquetas: $_GET - $_POST - PHP - Pregunta - URL - Web Votos: 0 - Respuestas: 1 - Vistas: 17 Compartir en: Google Facebook Twitter LinkedIn Link
 

Respuestas:

  • Fecha: 29-04-2017 00:33:30 Hola Alberto:

    Tanto en el form (<form action="?action=<?php echo isset($obj_categoria) ? 'actualizar' : 'registrar'; ?>" ... como posteriormente en los enlaces
    <a href="?action=editar&id=<?php echo urlencode($r->acronimo); ?>"><img src="icon_editthis.png" width="30px" height="30px"/></a>
    
    <a href="?action=eliminar&acronimo=<?php echo urlencode($r->acronimo); ?>"><img src="delete.png" width="30px" height="30px"/></a>

    estás pasando variables por GET cuando el form tiene el method="POST"

    Ello hace que la página no recoja los datos y no podamos ni editar ni eliminar los mismos.

    Sin poder asegurarlo (solo funcionaría si el valor del <input type="hidden" name="id" ... es el que queremos enviar vía GET), puedes editar el enlace
    <a href="?action=editar&id=<?php echo $_POST['id']; ?>">


    No obstante, y en lo que a seguridad que comentas, evitaría los $_REQUEST (que son muy útiles a la hora de programar pero mejor si los limitamos a $_GET, $_POST o $_COOKIE en producción, así como __GET (Métodos mágicos en PHP)
      Votos: 1 - Link respuesta
     
Para participar activamente de la comunidad primero debes autenticarte, ingresa al sistema.Iniciar Sesión
 
frjcbbae garagebible.com