Skip to content
Advertisement

PHP deleting record without passing id with $_GET

i’d like to know if there is a method to delete a record in php without passing it via $_GET, maybe with $_POST or other methods. I was using this code in the read.php page and

<table class="table table-bordered">
  <thead>
    <tr>
      <td>#</td>
      <td>Sigla</td>
      <td>Nome</td>
      <td>Bilancio</td>
      <td>Responsabile</td>
      <td>Azione</td>
    </tr>
  </thead>
  <tbody>
  <?php foreach ($rows as $row): ?>
    <tr>
      <td><?=$row['id']?></td>
      <td><?=$row['sigla']?></td>
      <td><?=$row['nome']?></td>
      <td><?=$row['bilancio']?></td>
      <td><?=$row['responsabile']?></td>
      <td class="actions">
        <a href="update.php?id=<?php echo $row['id']; ?>" class="edit">
          <i class="fas fa-pen fa-xs"></i>                
        </a>
        <a href="delete.php?id=<?php echo $row['id']; ?>" class="trash">
          <i class="fas fa-trash fa-xs"></i>
        </a>
      </td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>

as you can see for each record i create an href with the redirect to the “delete” or “update” page passing via $_GET the id. Is there a way to not show the id in the url? (maybe via $_POST), i’ve read hundreds of article but none of them answered to my question.

Advertisement

Answer

You need AJAX or a form

Using a link to delete is VERY dangerous since once viist from a crawler and your database is corrupt

I suggest something like this

  1. delegate the click to the container table
  2. use data-attributes for the ID
  3. Ajax using POST – I use fetch to do that here
let fetchData = {
  method: 'POST'
}
const url = "delete.php";
document.querySelector("form").addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.classList.contains("trash") && confirm("Delete "+this.id+"?")) {
    e.preventDefault();
    fetchData["body"] = {
      "id": this.getAttribute("data-id")
    };
    fetch(url, fetchData)
      .then(function() {
        console.log("deleted");
      });
  }
})
<a href="#" data-id="<?php echo $row['id']; ?>" class="trash">
  <i class="fas fa-trash fa-xs"></i>
</a>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement