How can I delete and modify records?

0

The thing is that I'm creating a table where I want the data already inserted can be modified or deleted. The problem is that I have no idea how to do it on my page model. the model is "Model View Controller". Any help?

There are some examples of my code.

Category.php

class Categoria {
private $id;
private $nombre;
private $db;

//CONEXION DB
public function __construct() {
    $this->db = DataBase::connect();
}

function getId() {
    return $this->id;
}

function getNombre() {
    return $this->nombre;
}

function setId($id) {
    $this->id = $id;
}

function setNombre($nombre) {
    $this->nombre = $this->db->real_escape_string($nombre);
}

public function getAll(){
    $categorias = $this->db->query("SELECT * FROM categorias ORDER BY id DESC;");
    return $categorias;
}

public function save(){
    $sql = "INSERT INTO categorias VALUES(NULL,'{$this->getNombre()}');";
    $save = $this->db->query($sql);

    $result = false;
    if($save){
        $result = true;
    }
    return $result;
}

}

CategoryController.php

require_once 'models / category.php';

class CategoryController {

public function index(){
    Utils::isAdmin();
    $categoria = new Categoria();
    $categorias = $categoria->getAll();

    require_once 'views/categoria/index.php';
}

public function crear(){
    Utils::isAdmin();
    require_once 'views/categoria/crear.php';
}

public function modificar(){
    Utils::isAdmin();
    require_once 'views/categoria/modificar.php';
}

public function save(){
    Utils::isAdmin();

    if(isset($_POST) && isset($_POST['nombre'])){
        //GUARDAR LA CATEGORIA EN BD
        $categoria = new Categoria();
        $categoria->setNombre($_POST['nombre']);
        $save = $categoria->save();
    }
    header('location:'.base_url.'categoria/index');
}

}

index.php

    DIRTER | REGISTRY     

<div id="presentacion">

    <!--BARRA DE NAVEGACION-->
    <nav class="navbar navbar-light bg-light navbar-expand-md py-2 shadow">
      <!--CONTAINER-->
      <div class="container">
        <!--LOGO-->
        <a href="<?=base_url?>" class="navbar-brand border-bottom">DIRTER</a>

      </div><!--FIN CONTAINER-->
    </nav><!--FIN BARRA NAVEGACION-->


    <!--CONTAINER-->
    <section class="container">  

        <a href="<?=base_url?>categoria/crear" class="btn btn-secondary rounded mt-3 btn-block">Crear categoria</a>

        <table class="table table-hover border mb-5" id="tabla-categoria">
            <thead class="thead-light">
                <tr>
                    <th>ID</th>
                    <th class="col-md-7">NOMBRE</th>
                    <th colspan="2">OPERACIONES</th>
                </tr>
            </thead>
            <?php while($cat = $categorias->fetch_object()): ?>
            <tbody>
                <tr>
                    <td><?= $cat->id; ?></td>
                    <td><?= $cat->nombre; ?></td>
                    <td><a href="<?=base_url?>categoria/modificar" class="px-3 py-1"><i class="fas fa-edit text-dark"></i></a></td>
                    <td><a href="<?=base_url?>categoria/eliminar" class="px-3 py-1"><i class="fas fa-trash-alt text-dark"></i></a></td>
                </tr>
            </tbody>
            <?php endwhile; ?>
        </table> 
    </section>
</div>

Thank you for your attention.

    
asked by Steven Angel Coaila Zaa 05.12.2018 в 05:02
source

2 answers

0

We use ajax (I will use it with JQuery since it is simpler, but it can be used with normal javascript).

We will create 2 files .php , one execute the update query and another to delete, we will call them for example actualizar.php and borrar.php . Then through javascript or JQuery we execute a click event and execute the ajax.

To achieve this instead of putting a <a> as you put, we will use a <span> we will change it for a simple reason: we do not need to go anywhere in (unlike a). You can also use a <div>

Important to put a class and not an id, since ids are unique you have n elements

Buttons:

<td><span class="modificar px-3 py-1"><i class="fas fa-edit text-dark"></i></span></td>
<td><span class="eliminar px-3 py-1"><i class="fas fa-trash-alt text-dark"></i></span></td>

JQuery Delete:

   $(".eliminar").click(function(){
      var fila=$(this).parent().parent();
      var id =fila.find("td:first-child").html();
      if(confirm("Desea de verdad eliminar el "+id+"?")==true){
         jQuery.ajax({
           url:"eliminar.php",
           type:"POST",
           data:{del_id:id},
           success:function(){
              $(fila).fadeOut(function(){
                  $(this).remove();
              });
           },
           error:function(errors){
                  alert("Error: "+errors);
           }
         });
      }
   });

For the modification part we will make that when we click on the icon the content can be edited through an input, for this we will need to add a class and an input to the td of the name. (I assume that the id is an auto_incrementative field)

<td class="nombre"><input type="hidden" name="nombre" val=<?= $cat->nombre; ?>></td>

When you click the 1st time the class will be changed to another class so you can control 2 actions in the same button

JQuery Modify:

   $(".modificar").click(function(){
      $(this).addClass("modificar2");
      $(this).removeClass("modificar");
      var fila=$(this).parent().parent();
      var id =fila.find("td:first-child").html();
      $(fila).find(".nombre").find("input").attr("type","text");
   });
   $(".modificar2").click(function(){
      $(this).addClass("modificar");
      $(this).removeClass("modificar2");
      var fila=$(this).parent().parent();
      var id =fila.find("td:first-child").html();
      if(confirm("Desea de verdad eliminar el "+id+"?")==true){
         $(fila).find(".nombre").find("input").attr("type","hidden");
         var valor=$(fila).find(".nombre").find("input").val();

         jQuery.ajax({
           url:"modificar.php",
           type:"POST",
           data:{upd_id:id,nombre:valor},
           success:function(){
              $('#tabla-categoria').load("#tabla-categoria");
           },
           error:function(errors){
                  alert("Error: "+errors);
           }
         });
      }
   });
    
answered by 05.12.2018 / 06:13
source
0

Hi steve, you can use Ajax for this occasion

Example

 $('#BorrarRegistro').click( function(event) {
    event.preventDefault();

    var form = $('#modal-body2 form'),
        url = 'fichero.php',
        method = $('input[name=_method]').val() == undefined ? 'POST' : 'PUT';

    $.ajax({
        url : url,
        method: method,
        success: function (response) {
            //con esto actualizas la tabla
            $('#idTabla').load(" #idTabla");
        },
        error : function(xhr) {
            alert('error');
        }
    })
});
    
answered by 05.12.2018 в 05:40