I have a problem with my edit button

1

I already have everything, I just need the edit button but it is not edited, I pass the HTML and the php.

<?php include('php/registrar.php');
if (isset($_GET['edit'])) {
      $id=$_GET['edit'];
      $editar_estado=true;
      $rec=mysqli_query($conexion,"SELECT * FROM tarjetas WHERE id=$id");
      $record=mysqli_fetch_array($rec);
      $nombre=$record['nombre'];
      $apellido=$record['apellido'];
      $correo=$record['correo'];
      $clave=$record['clave'];
      $telefono=$record['telefono'];
      $id=$record['id'];
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">

    <!-- Estilos -->
    <link rel="stylesheet" href="css/estilos.css">
    <link rel="stylesheet" href="css/tablas.css">
    <link rel="stylesheet" href="css/avisos.css">

    <title>Hello, world!</title>
    </head>
    <body>
<?php if (isset($_SESSION['msg'])):?>
<div class="msg">
  <?php
echo $_SESSION['msg'];
unset($_SESSION['msg']);
   ?>
</div>
<?php endif ?>
    <h1>Plantilla</h1>
    <form action="php/registrar.php" method="post" class="form-register" onsubmit="return validar();">
    <input type="hidden" name="id" value="<?php echo $id; ?>">
    <h2 class="form_titulo">Introduzca sus datos</h2>
    <div class="contenedor-inputs">
      <input type="text"     name="nombre"     id="nombre"      placeholder="Nombre"       class="input-100" value="<?php echo $nombre; ?>" >
      <input type="text"     name="apellido"   id="apellido"    placeholder="Apellido"     class="input-100" value="<?php echo $apellido; ?>" >
      <input type="email"    name="correo"     id="correo"      placeholder="Correo"       class="input-100" value="<?php echo $correo; ?>">
      <input type="password" name="clave"      id="clave"       placeholder="clave"        class="input-100" value="<?php echo $clave; ?>" >
      <input type="tel"      name="telefono"   id="telefono"    placeholder="Telefono"     class="input-100" value="<?php echo $telefono; ?>">
    <!-- <input type="submit"   name="enviar"  id="enviar"   value="Enviar"   class="btn_enviar" >-->
<?php  if ($editar_estado == false): ?>
  <button type="submit" name="btn_enviar" class="btn_enviar">Enviar</button>
<?php else : ?>
  <button type="submit" name="btn_actualizar" class="btn_actualizar">Actualizar</button>
<?php endif ?>
    </div>
    </form>

    <!--Tablas-->
    <div class="contenedor">
    <table>
    <thead>
    <tr>
        <th>#</th>
        <th>nombre</th>
        <th>Apellido</th>
        <th>Correo</th>
        <th>clave</th>
        <th>telefono</th>
        <th colspan="2">Action</th>
    </tr>
    </thead>
    <tbody>
  <?php while ($row=mysqli_fetch_array($resultado)) { ?>
  <tr>
      <td><?php echo $row["id"];       ?></td>
      <td><?php echo $row["nombre"];   ?></td>
      <td><?php echo $row["apellido"]; ?></td>
      <td><?php echo $row["correo"];   ?></td>
      <td><?php echo $row["clave"];    ?></td>
      <td><?php echo $row["telefono"]; ?></td>
      <td>
        <a class="btn_editar"   href="Index.php?edit=<?php echo $row['id']; ?>" >Editar</a>
      </td>
      <td>
        <a class="btn_eliminar" href="php/registrar.php?del=<?php echo $row['id']; ?>">Eliminar</a>
      </td>
  </tr>
<?php }?>
    </tbody>
    </table>
    </div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Optional JavaScript -->
    <script type="js/validar.js"></script>
    </script>
  </body>
</html>
I think my SQL statement is wrong and if you can give me Injection SQL advice

<?php
session_start();

//variables
$nombre="";
$apellido="";
$correo="";
$clave="";
$telefono="";
$id=0;
$editar_estado=false;

//conexion
$conexion=mysqli_connect('localhost','root','koUeARe1bX4YlfrE','plantilla');

//Boton Enviar
  if (isset($_POST['btn_enviar'])) {
  $nombre=  $_POST["nombre"];
  $apellido=$_POST["apellido"];
  $correo=  $_POST["correo"];
  $clave=   $_POST["clave"];
  $telefono=$_POST["telefono"];

//Consulta para guardar
  $insertar ="INSERT INTO tarjetas(nombre, apellido, correo, clave, telefono)
  VALUES ('$nombre','$apellido','$correo','$clave','$telefono');";
  $query=mysqli_query($conexion,$insertar);
  $_SESSION['msg']="Usuario guardado";
  header('Location:../Index.php');
}

//Boton Actualizar
if (isset($_POST['btn_actualizar'])) {
  $nombre  = mysqli_real_escape_string($_POST['nombre']);
  $apellido= mysqli_real_escape_string($_POST['apellido']);
  $correo  = mysqli_real_escape_string($_POST['correo']);
  $clave   = mysqli_real_escape_string($_POST['clave']);
  $telefono= mysqli_real_escape_string($_POST['telefono']);
  $id      = mysqli_real_escape_string($_POST['id']);

  mysqli_query($conexion,"UPDATE tarjetas SET nombre='$nombre', apellido='$apellido', correo='$correo', clave='$clave', telefono='$telefono' WHERE id='$id'");
  $_SESSION['msg']="Usuario actualizado";
  header('location:../Index.php');
}
//boton de borrar
if (isset($_GET['del'])) {
  $id=$_GET['del'];
  mysqli_query($conexion,"DELETE FROM  tarjetas WHERE id=$id");
  $_SESSION['msg']="Usuario borrado";
  header('location:../Index.php');
}


//registrar informacion
$mostrar ="SELECT * FROM tarjetas;";
$resultado=mysqli_query($conexion,$mostrar)
//cerrar conexion

 ?>
    
asked by oscar hernan 04.07.2018 в 22:02
source

1 answer

0

Try this for the update function.

I briefly comment on what my proposal consists of:

  • It is a controlled code, which is collecting in the variable $arrStatus everything that happens, success or errors of the code.
  • To collect the POST values we will use ternary operators, asking if that value is not empty. If it is, we assign it NULL . I like this form, because then we can restrict the query. For example, if the essential columns are null, we stop the UPDATE attempt, since we can not allow those columns to be stored with null values. It is assumed that, on the other hand, those columns will have the restriction NOT NULL in the database. Here I have assumed that there are three such essential columns . You can change that according to your design.
  • We will eliminate mysqli_real_escape_string , because we will use prepared queries. It is the best measure to protect the SQL injection code.
  • In the prepared consultation phase, pay close attention to the function mysqli_stmt_bind_param ... there I have assumed that all the columns involved are alphanumeric, except the last one, which is id ... so at the end there is a i . If the id is alphanumeric, you must change the i for a s .
  • The code controls all the neuralgic points of the preparation and that can fail, picking up the error messages of those failures.
  • The code does not innocently show that there was an update. That can only be determined if there were rows affected.
  • At the end of everything the key status of our utility array is checked and only if TRUE the session variable is updated and the redirection is made. You can change that part to your liking. For example, you can do the same redirection, but correctly reporting what happened. Well as you see, a thousand reasons may occur for the update does not occur. And this with or without errors. Imagine that the condition of WHERE is not fulfilled. In that case there will be no update. All of that must be controlled in the code.

The proposal, once indicated all the above, would be this:

$arrStatus=array();
if (isset($_POST['btn_actualizar'])) {
    /*Usamos operadores ternarios para guardar los valores del POST*/
    $nombre     = (empty($_POST['nombre'])) NULL ? $_POST['nombre'];
    $apellido   = (empty($_POST['apellido'])) NULL ? $_POST['apellido'];
    $correo     = (empty($_POST['correo'])) NULL ? $_POST['correo'];
    $clave      = (empty($_POST['clave'])) NULL ? $_POST['clave'];
    $telefono   = (empty($_POST['telefono'])) NULL ? $_POST['telefono'];
    $id         = (empty($_POST['id'])) NULL ? $_POST['id'];

  /*
        *Bloqueamos si algún valor esencial es NULL
        *aquí supongo que id, nombre y apellido no pueden ser nulos
        *si hay más los agregas a la condición
  */

    if ($nombre && $apellido && $id){
        $sql="UPDATE tarjetas SET nombre=?, apellido=?, correo=?, clave=?, telefono=? WHERE id=?";
        if ($stmt = mysqli_prepare($conexion, $sql)){
                mysqli_stmt_bind_param($stmt, "sssssi", $nombre,$apellido,$correo,$clave,$telefono,$id);
                if (mysqli_stmt_execute($stmt)){
                    $totalFilas=mysqli_affected_rows($conexion);
                    if($totalFilas>0)
                        $arrStatus=array("status"=>TRUE, "msg"=>"Se actualizaron $totalFilas filas");
                    }else{
                        $arrStatus=array("status"=>FALSE, "msg"=>"Ninguna fila actualizada");
                    }
                 }else{
                    $msg="La actualización falló: ".mysqli_error($conexion);    
                    $arrStatus=array("status"=>FALSE, "msg"=>"$msg");
                }
        }else{
              $msg="La preparación falló: ".mysqli_error($conexion);
              $arrStatus=array("status"=>FALSE, "msg"=>"$msg");               
        }     
    }else{
          $arrStatus=array("status"=>FALSE, "msg"=>"Hay datos esenciales que son nulos o están en blanco");

    }
    /*Verificamos el estado del array*/ 
    if ($arrStatus["status"]==TRUE){
        $_SESSION['msg']="Usuario actualizado";
        header('location:../Index.php');
    }else{
        echo $arrStatus["msg"];
    }
}
    
answered by 04.07.2018 в 23:07