Updated PHP - HTML form

0

I have a form to add data to a table (visual in HTML) and to the database (in a table called "Cabanas").

Doubts:

1) Why is not the table automatically updated when you click "Save"? And you only see the cabin added when we update the page.

2) When we update we see that it inserts the cabin correctly but it gives it an ID = 0, when all the IDs in my table start from (1-N) and regenerate automatically. That is, all the cabins I want to add assigns ID = 0 , that is, it only allows me to add one but gives a "duplicate primary key" error.

SQL Code:

CREATE TABLE CABANAS (
    idcabana INT PRIMARY KEY NOT NULL,
    nombre VARCHAR(50) NOT NULL,
    capacidad INT NOT NULL, 
    descripcion VARCHAR(200) NOT NULL,
    precio DECIMAL(6,2) NOT NULL, /*Precio: cabaña/noche */
    CHECK (capacidad>0 AND capacidad<=10)
);

INSERT INTO CABANAS (idcabana, nombre, capacidad, descripcion, precio) VALUES 
(1, "CABAÑA1", 9, "HABITACIÓN DE CABAÑA MUY GRANDE CON TODOS LOS ACCESORIOS.", 150),
(2, "CABAÑA2", 6, "CUATRO CAMAS CON CAPACIDAD PARA 7 PERSONAS. IDÓNEA PARA FAMILIAS.", 92),
(3, "CABAÑA3", 4, "DOS CAMAS, CON OPCIÓN A UNA SUPLETORIA. CABAÑA MUY CÓMODA Y AMIGABLE.", 78);

HTML Code:

<?php
    require_once "Clases/BD.php";
    require_once "Clases/Cabanas.php";
    require_once "conexion.php";

    //Iniciar una nueva sesión o reanudar la existente.
    session_start();
    //Si existe la sesión "administrador"..., la guardamos en una variable.
    if (isset($_SESSION['administrador'])){
        $administrador = $_SESSION['administrador'];
    }
?>

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8">
        <title>Panel del administrador</title>
    </head>
    <body>
        <div id="sesion_administrador">
            <?php 
            if(isset($_SESSION['administrador'])){
                echo "Bienvenido ".$administrador."&nbsp;&nbsp;&nbsp;";
                echo "<a href='salir_administrador.php?salir=1'>Salir</a>"; //GET
                //_REQUEST = $_POST o $_GET
                if(isset($_REQUEST["salir"])){
                    unset($_SESSION["administrador"]);
                    header("Refresh:0; url=iniciar_sesion_administrador.php");
                }
            }
            ?>
        </div>

        <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="tabla_datos_cabana" id="tabla_datos_cabana" method="POST">
            <div id="mostrar_cabanas">
            <br/><br/><br/>
                <table class="table table-striped" name="tabla" width="600" border="2" cellspacing="3" cellpadding="3" style="font-size: 10pt">
                    <center>
                        <tr>
                            <thead style="background-color:#A9F5A9">
                                <td width=\"150\">
                                    <font face="verdana" color="blue"><b><center>ID Cabaña</center></b></font>
                                </td>
                                <td width=\"250\">
                                    <font face="verdana" color="blue"><b><center>Nombre</center></b></font>
                                </td>
                                <td width=\"150\">
                                    <font face="verdana" color="blue"><b><center>Modificar</center></b></font>
                                </td>
                                <td width=\"150\">
                                    <font face="verdana" color="blue"><b><center>Eliminar</center></b></font>
                                </td>
                            </thead>
                        </tr>   
                        <?php
                        $datos = BD::obtenerCabanas();
                        foreach($datos as $cabana){
                            echo "<tr>";
                                echo "<td width=\"150\"><font face=\"verdana\"><font size='2'><center>".$cabana->getIdcabana()."</center></font></font></td>";
                                echo "<td width=\"250\"><font face=\"verdana\"><font size='2'><center>".$cabana->getNombre()."</center></font></font></td>";
                                echo "<td width=\"150\"><font face=\"verdana\"><font size='2'><center>"?> 
                                    <a href="modificar.php?idcabana=<?=$cabana->getIdcabana();?>">
                                        <img src="imagenes/modificar.png" height='24' width='26' onmouseover="this.src='imagenes/modificar_in.png';" onmouseout="this.src='imagenes/modificar.png';">
                                    </a> <?php "</center></font></font></td>";
                                echo "<td width=\"150\"><center><input type='checkbox' name='marcados[]' id='marcados[]' value=".$cabana->getIdcabana()."></center>";
                         echo "</tr>";
                        }
                        ?>
                    </center>
                </table>

                <!-- Botón NUEVA cabaña -->
                <div class="boton_anadir" class="table-responsive" align="left">
                    <font face="verdana">
                        <b><input type="submit" style="width:200px; height:28px;" name="nueva_cabana" id="nueva_cabana" value="Añadir cabaña"></b>
                    </font><br/>
                </div>

                <!-- Botón ELIMINAR cabaña/s -->
                <div class="boton_eliminar" class="table-responsive" align="left">
                    <font face="verdana">
                        <b><input type="submit" style="width:200px; height:28px;" name="eliminar_cabanas" id="eliminar_cabanas" onclick="return confirm('¿Deseas realmente eliminar estas cabañas?');" value="Eliminar cabañas"></b>
                    </font><br/>
                </div>

                <?php
                //Si pulsamos el botón "Eliminar cabañas"...
                if(isset($_POST['eliminar_cabanas'])){
                    if(empty($_POST['marcados'])){
                        echo "<h4><center>No se ha seleccionado ninguna cabaña.</center></h4>";
                    }else{
                        foreach($_POST['marcados'] as $valor){
                            //Nos conectamos a la base de datos.
                            $conexion = mysqli_connect("localhost", "root", "root", "osmarrural");
                            //Realizamos la consulta.
                            $sql = sprintf("DELETE FROM cabanas WHERE idcabana='%d'", $valor);
                            $resultado = mysqli_query($conexion, $sql);
                            /*
                            $mysqli = new mysqli_connect("localhost", "root", "root", "osmarrural");
                            $stmt = $mysqli->prepare("DELETE FROM cabanas WHERE idcabana = ?");
                            $stmt->bind_param('i', $valor);
                            $stmt->execute(); 
                            $stmt->close();
                            */
                        }
                        echo "<meta http-equiv=\"refresh\" content=\"0; URL=panel_administrador.php\">";
                    }
                }
            ?>
            </div>
        </form>
        <br/><br/><br/>
        <!-- Añadir una cabaña -->
        <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="añadir_cabanas" id="añadir_cabanas" method="POST">
            <div id="añadir_cabanas">
                <label for="nombre">Nombre: </label> <input type="text" id="nombre" name="nombre"/></label><br/><br/>
                <label for="capacidad">Capacidad: </label>
                <?php
                echo "<select name='capacidad'>";
                for($i=1; $i<11; $i++){
                    if($i==1){
                        echo "<option value='$i' selected='selected'>$i</option>";
                    }else{
                        echo "<option value='$i'>$i</option>";
                    }
                }
                echo "</select>";
                ?><br/><br/>
                <label for="descripcion">Descripción: </label> <input type="text" id="descripcion" name="descripcion"/></label><br/><br/>
                <label for="precio">Precio: </label> <input type="text" id="precio" name="precio"/></label><br/><br/>

                <input type="submit" value="Guardar" id="guardar" name="guardar"/>
                <input type="reset" value="Resetear" id="resetear" name="resetear"/>
                <?php
                //Si pulsamos el botón "Guardar"...
                if(isset($_POST["guardar"])){
                    $nombre = $_POST["nombre"];
                    $capacidad = $_POST["capacidad"];
                    $descripcion = $_POST["descripcion"];
                    $precio = $_POST["precio"];
                    //Llamamos al método "anadirCabana" y le pasamos los parámetros del formulario.
                    BD::anadirCabana($nombre, $capacidad, $descripcion, $precio);
                }
                ?>
            </div>
        </form>
    </body>
</html>

PHP code addCabana function:

static public function anadirCabana($nombre, $capacidad, $descripcion, $precio){
        $ejecucion = self::Conexion();
        $sql = "INSERT INTO cabanas (nombre, capacidad, descripcion, precio) VALUES ('".$nombre."', ".$capacidad.", '".$descripcion."', ".$precio.")";
        $ok = $ejecucion->exec($sql);
        if($ok==1){
            echo "Cabaña agregada.";
        }else{
            echo "Cabaña NO agregada.";
        }
    }

3) How could you put the following instruction in a more professional way so that the "echo" is not shown on the screen and go all the way behind?

if($ok==1){
    echo "Cabaña agregada.";
}else{
    echo "Cabaña NO agregada.";
}
    
asked by omaza1990 29.11.2017 в 10:20
source

1 answer

3

I'll answer for points:

1) Why is not the table automatically updated when you press "Save"? And you only see the cabin added when we update the page.

The reason is that you send the form to the same page where you show results, this code will be executed in linear order, if you show the results before calling the function BD::anadirCabana($nombre, $capacidad, $descripcion, $precio); the result is that the SELECT is done for get the cabins before the INSERT , since your INSERT is the last process that is done in the PHP file. I modified the code:

<?php
    require_once "Clases/BD.php";
    require_once "Clases/Cabanas.php";
    require_once "conexion.php";

    //Iniciar una nueva sesión o reanudar la existente.
    session_start();
    //Si existe la sesión "administrador"..., la guardamos en una variable.
    if (isset($_SESSION['administrador'])){
        $administrador = $_SESSION['administrador'];
    }

   //Si pulsamos el botón "Guardar"... 
   //EDITO: Se sube esta parte del código a la parte superior, para que se realice el insert antes que el select.
    if(isset($_POST["guardar"])){
        $nombre = $_POST["nombre"];
        $capacidad = $_POST["capacidad"];
        $descripcion = $_POST["descripcion"];
        $precio = $_POST["precio"];
        //Llamamos al método "anadirCabana" y le pasamos los parámetros del formulario.
        BD::anadirCabana($nombre, $capacidad, $descripcion, $precio);
    }
?>



<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8">
        <title>Panel del administrador</title>
    </head>
    <body>
        <div id="sesion_administrador">
            <?php 
            if(isset($_SESSION['administrador'])){
                echo "Bienvenido ".$administrador."&nbsp;&nbsp;&nbsp;";
                echo "<a href='salir_administrador.php?salir=1'>Salir</a>"; //GET
                //_REQUEST = $_POST o $_GET
                if(isset($_REQUEST["salir"])){
                    unset($_SESSION["administrador"]);
                    header("Refresh:0; url=iniciar_sesion_administrador.php");
                }
            }
            ?>
        </div>

        <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="tabla_datos_cabana" id="tabla_datos_cabana" method="POST">
            <div id="mostrar_cabanas">
            <br/><br/><br/>
                <table class="table table-striped" name="tabla" width="600" border="2" cellspacing="3" cellpadding="3" style="font-size: 10pt">
                    <center>
                        <tr>
                            <thead style="background-color:#A9F5A9">
                                <td width=\"150\">
                                    <font face="verdana" color="blue"><b><center>ID Cabaña</center></b></font>
                                </td>
                                <td width=\"250\">
                                    <font face="verdana" color="blue"><b><center>Nombre</center></b></font>
                                </td>
                                <td width=\"150\">
                                    <font face="verdana" color="blue"><b><center>Modificar</center></b></font>
                                </td>
                                <td width=\"150\">
                                    <font face="verdana" color="blue"><b><center>Eliminar</center></b></font>
                                </td>
                            </thead>
                        </tr>   
                        <?php
                        $datos = BD::obtenerCabanas();
                        foreach($datos as $cabana){
                            echo "<tr>";
                                echo "<td width=\"150\"><font face=\"verdana\"><font size='2'><center>".$cabana->getIdcabana()."</center></font></font></td>";
                                echo "<td width=\"250\"><font face=\"verdana\"><font size='2'><center>".$cabana->getNombre()."</center></font></font></td>";
                                echo "<td width=\"150\"><font face=\"verdana\"><font size='2'><center>"?> 
                                    <a href="modificar.php?idcabana=<?=$cabana->getIdcabana();?>">
                                        <img src="imagenes/modificar.png" height='24' width='26' onmouseover="this.src='imagenes/modificar_in.png';" onmouseout="this.src='imagenes/modificar.png';">
                                    </a> <?php "</center></font></font></td>";
                                echo "<td width=\"150\"><center><input type='checkbox' name='marcados[]' id='marcados[]' value=".$cabana->getIdcabana()."></center>";
                         echo "</tr>";
                        }
                        ?>
                    </center>
                </table>

                <!-- Botón NUEVA cabaña -->
                <div class="boton_anadir" class="table-responsive" align="left">
                    <font face="verdana">
                        <b><input type="submit" style="width:200px; height:28px;" name="nueva_cabana" id="nueva_cabana" value="Añadir cabaña"></b>
                    </font><br/>
                </div>

                <!-- Botón ELIMINAR cabaña/s -->
                <div class="boton_eliminar" class="table-responsive" align="left">
                    <font face="verdana">
                        <b><input type="submit" style="width:200px; height:28px;" name="eliminar_cabanas" id="eliminar_cabanas" onclick="return confirm('¿Deseas realmente eliminar estas cabañas?');" value="Eliminar cabañas"></b>
                    </font><br/>
                </div>

                <?php
                //Si pulsamos el botón "Eliminar cabañas"...
                if(isset($_POST['eliminar_cabanas'])){
                    if(empty($_POST['marcados'])){
                        echo "<h4><center>No se ha seleccionado ninguna cabaña.</center></h4>";
                    }else{
                        foreach($_POST['marcados'] as $valor){
                            //Nos conectamos a la base de datos.
                            $conexion = mysqli_connect("localhost", "root", "root", "osmarrural");
                            //Realizamos la consulta.
                            $sql = sprintf("DELETE FROM cabanas WHERE idcabana='%d'", $valor);
                            $resultado = mysqli_query($conexion, $sql);
                            /*
                            $mysqli = new mysqli_connect("localhost", "root", "root", "osmarrural");
                            $stmt = $mysqli->prepare("DELETE FROM cabanas WHERE idcabana = ?");
                            $stmt->bind_param('i', $valor);
                            $stmt->execute(); 
                            $stmt->close();
                            */
                        }
                        echo "<meta http-equiv=\"refresh\" content=\"0; URL=panel_administrador.php\">";
                    }
                }
            ?>
            </div>
        </form>
        <br/><br/><br/>
        <!-- Añadir una cabaña -->
        <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="añadir_cabanas" id="añadir_cabanas" method="POST">
            <div id="añadir_cabanas">
                <label for="nombre">Nombre: </label> <input type="text" id="nombre" name="nombre"/></label><br/><br/>
                <label for="capacidad">Capacidad: </label>
                <?php
                echo "<select name='capacidad'>";
                for($i=1; $i<11; $i++){
                    if($i==1){
                        echo "<option value='$i' selected='selected'>$i</option>";
                    }else{
                        echo "<option value='$i'>$i</option>";
                    }
                }
                echo "</select>";
                ?><br/><br/>
                <label for="descripcion">Descripción: </label> <input type="text" id="descripcion" name="descripcion"/></label><br/><br/>
                <label for="precio">Precio: </label> <input type="text" id="precio" name="precio"/></label><br/><br/>

                <input type="submit" value="Guardar" id="guardar" name="guardar"/>
                <input type="reset" value="Resetear" id="resetear" name="resetear"/>
            </div>
        </form>
    </body>
</html>

2) When we update we see that it inserts the cabin correctly but it gives it an ID = 0, when all the IDs in my table start from (1-N) and regenerate automatically. That is, all the cabins I want to add assigns ID = 0, that is, it only allows me to add one if it fails to "duplicate primary key".

If you have set the field as primary and only, but not as auto-increment , you must change that property to be able to increase it automatically. The SQL would be:

ALTER TABLE CABANAS MODIFY COLUMN idcabana auto_increment

3) How could you put the following instruction in a more professional way so that the "echo" is not shown on the screen and go all the way behind?

I do not understand exactly what you mean from behind, but if you do not want to show any value when you do the process, you do not need to do an echo:

static public function anadirCabana($nombre, $capacidad, $descripcion, $precio){
    $ejecucion = self::Conexion();
    $sql = "INSERT INTO cabanas (nombre, capacidad, descripcion, precio) VALUES ('".$nombre."', ".$capacidad.", '".$descripcion."', ".$precio.")";
    $ok = $ejecucion->exec($sql);

    if($ok==1) return true;
    else return false;
}

In this case, we will return TRUE or FALSE , since it is recommended to have a control of our processes, that then you want to show something and verify if the answer was TRUE or FALSE to show a message, no, you do not check and nothing is shown.

Greetings,

    
answered by 29.11.2017 / 10:32
source