My Update does not work

0

I'm trying this:

 <?php

    session_start();
    require 'conexion.php';

    $nombre = $_POST['nombre'];
    $emai   = $_POST['emai'];
    $pass   = $_POST['pass'];
    $tel    = $_POST['tel'];
    $dir    = $_POST['dir'];
    $id     = $_SESSION['usuario']['ID'];

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Oops: " . $conn->connect_error);
    }

    if (isset($_SESSION['usuario'])) {

        $cambio = "UPDATE Usuarios SET name='$nombre', email='$emai', password='$pass', phone='$tel', address='$dir' WHERE ID='$id'";        

        if (($result=$conn->query($cambio)) === true) {
            echo $_SESSION['usuario']['name'];
        } else {
            echo "Error: ";
        }

    } else {

        echo"oops";

    }

    $conn->close();

?>

With this form:

<form action="vcambio.php" method="post">
    <div class="group">
        <input type="text" name="nombre" required>
        <span class="highlight"></span>
        <span class="bar"></span>
        <label>cambiar nombre</label>
    </div>
    <div class="group">
        <input type="email" name="emai" required>
        <span class="highlight"></span>
        <span class="bar"></span>
        <label>Cambiar Email</label>
    </div>
    <div class="group">
        <input type="password" name="pass" required>
        <span class="highlight"></span>
        <span class="bar"></span>
        <label>Cambiar Contrase&ntilde;a</label>
    </div>
    <div class="group">
        <input type="text" name="tel" required>
        <span class="highlight"></span>
        <span class="bar"></span>
        <label>Cambiar Telefono</label>
    </div>
    <div class="group">
        <input type="text" name="dir" required>
        <span class="highlight"></span>
        <span class="bar"></span>
        <label>Cambiar direccion</label>
    </div>    
    <input type="submit" name="sumbitt" value="Guardar Cambios"</input>
</form>

<?php
    if (isset($_POST['submitt'])) {
        require ("vcambio.php");
    }
?>

I can not find the error when I execute it. Print the variables from the previous session. It does not throw me error but it does not update the variables, when I consult it in phpmyadmin it follows the same as before.

    
asked by ger 11.11.2017 в 14:36
source

4 answers

1

I propose that you try this solution. In it:

  • I apply the principle of queries prepared to give security to the code
  • I write a code forced to talk . Throughout the journey, you add a message to the variable $arrMensaje , which is printed at the end to tell you what happened in the code. I call this principle code controlled . I believe that the programmer should never write a code that fails without him knowing why it fails. Here he will tell you whatever.
  • For the code to work, you must control some things, for example your column ID is it all written in upper case ?. Note that the table and column names are case sensitive . Well, if you have it badly written you will know, the code will tell you.
  • Also, when doing the binding, you need to confirm if your column ID is of type VARCHAR in the database or if it is numeric ...
  • That said, here we go. I hope you can prove it and comment on the result:

    <?php
    
        session_start();
        require 'conexion.php';
    
        $nombre = $_POST['nombre'];
        $emai   = $_POST['emai'];
        $pass   = $_POST['pass'];
        $tel    = $_POST['tel'];
        $dir    = $_POST['dir'];
        $id     = $_SESSION['usuario']['ID'];
    
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
    
        // Check connection
        if (!$conn) {
    
            $arrMensaje=array("mensaje"=>"Error: Fallo de conexión");
    
        }else{
    
            if (isset($_SESSION['usuario'])) {
    
                $strSQL = "UPDATE Usuarios SET name=?, email=?, password=?, phone=?, address=? WHERE ID=?";      
                $stmt=$conn->prepare($strSQL);
    
    
                if ($stmt){
    
                    $stmt->bind_param("sssssi", $nombre,$emai,$pass,$tel,$dir,$id);
    
                    if ($stmt->execute()) {
                        $intFilas=$stmt->affected_rows;  
                        $arrMensaje=array("mensaje"=>"Actualizado. Filas afectadas: ".$intFilas.PHP_EOL."Sesión: ".$_SESSION['usuario']['name']);
    
                    }else{
    
                        $arrMensaje=array("mensaje"=>"No se cumplieron los criterios o clave duplicada " . $stmt->error);
                    }
    
                }else{
    
                    $arrMensaje=array("mensaje"=>"Error: La consulta falló No Error: ".$stmt->errno . "Causa: " . $stmt->error);            
                    $stmt->close();
                }
    
    
            } else {
    
                $arrMensaje=array("mensaje"=>"No hay sesión de usuario");
    
            }
    
            $conn->close();
    
        }
    
        echo $arrMensaje["mensaje"];
    ?>
    
        
    answered by 11.11.2017 / 17:33
    source
    1

    You would have to pass a user ID per session ... so that the update of your WHERE is governed there (where is your problem)

    In what you went through codes, there is no variable "$ email", but "$ emai"

    WHERE email='$email'
    

    (--- Approach ---) If I have all my data and email "[email protected]" I want to change to "[email protected]" in your WHERE you will find the email [email protected] to change it to [email protected] and will not search to [email protected] (according to the query you are using, unless your current mail is saved as a session or you pass it through input hydden (which is later to be implemented in a few more lines to control that it is not manipulated before sending it) to php + sql))

        
    answered by 11.11.2017 в 15:15
    1
    <?php
    
        session_start();
        require conexion.php;
    
        extract($_POST); // importa a la lista de variables lo que llega por $_POST
    
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
    
        // Check connection
        if ($conn->connect_error) {
            die("Oops: " . $conn->connect_error);
        }
    
        if (isset($_SESSION['usuario'])) {
    
            $cambio = "UPDATE Usuarios SET name='$nombre', email='$emai', password='$pass', phone='$tel', address='$dir' WHERE ID='$id'";        
    
            if (($conn->query($cambio))) 
            {
                echo $_SESSION['usuario']['name'];
            } else {
                echo "Error: ";
            }
    
        } else {
    
            echo"oops";
    
        }
    
        $conn->close();
    
    ?>
    

    Anyway, since I can not see the file conexion.php, it is impossible to find out if the connection is well made ...

    I hope I helped you something.

    Greetings

        
    answered by 11.11.2017 в 15:41
    1

    Another error apart those that have been modified by the comments is in the next step:

    if (($result=$conn->query($cambio)) === true) {
    

    I see too many open and close keys () , in fact I did a test, and I send an error.

      

    error: Fatal error: Call to a member function query() on null in... , like on that line.

    You could do something like this:

    $result = $conn->query("UPDATE Usuarios SET name='$nombre', email='$emai', password='$pass', phone='$tel', address='$dir' WHERE ID=$id"); 
    
    if (true===$result) { }
    

    or

    if ($conn->query($cambio) === true)      
    


    A possible example:

    conexion.php

    $conn = new mysqli("servidor", "usuario", "contraseña", "BaseDatos");
    
    /* verificar conexión */
    if (mysqli_connect_errno()) {
        printf("Conexión fallo: %s\n", mysqli_connect_error());
        exit();
    } else {
        //echo 'Existe conexión.';
    }
    

    UPDATE

    <?php
        session_start();        
        //Reset
        $nombre = $emai = $pass = $tel = $dir = $id = NULL;
    
        //Si esta definido el formulario
        if (isset($_POST['sumbitt'])) {     
            //Obtener datos del formulario
            $nombre = $_POST['nombre'];
            $emai   = $_POST['emai'];
            $pass   = $_POST['pass'];
            $tel    = $_POST['tel'];
            $dir    = $_POST['dir'];
            $id     = $_SESSION['usuario']['ID'];
    
            //Si esta definido la sesion.
            if (isset($_SESSION['usuario'])) {
                //Verdadero datos a trabajar.
                if ($nombre && $emai && $pass && $tel && $dir && $id) {
                    //Conexion (Importante llamar a la conexión dodne vas a trabajar con el).
                    require 'conexion.php';
                    //Sentencia
                    $result = $conn->query("UPDATE Usuarios SET name='$nombre', email='$emai', password='$pass', phone='$tel', address='$dir' WHERE ID=$id");        
                    //Comprabación si se ejecuto la sentencia.
                    if (true===$result) {
                        echo $_SESSION['usuario']['name'];
                    } else {
                        exit('Fallo el update: ' . htmlspecialchars($conn->error));
                    }                   
                }
            } else {
                echo"oops hubo un error en tu sesión.";
            }   
        }
    
    ?>
    
      

    Note: I advise you for security use mysqli prepare statements or PDO. I also advise you to read well    How to avoid SQL injection in PHP ?

        
    answered by 11.11.2017 в 16:45