PHP Logical Exclusion

2

I'm starting my studies in PHP. I need to make a logical exclusion and although I have already found enough content on the topic, I can not find exactly how to do logical exclusion in PHP. Mine I did so (physical):

function remove( $table = null, $id = null ) {
  $database = open_database();

  try {
    if ($id) {
      $sql = "DELETE FROM " . $table . " WHERE id = " . $id;
      $result = $database->query($sql);
      if ($result = $database->query($sql)) {       
        $_SESSION['message'] = "Registro Removido com Sucesso.";
        $_SESSION['type'] = 'success';
      }
    }
  } catch (Exception $e) { 
    $_SESSION['message'] = $e->GetMessage();
    $_SESSION['type'] = 'danger';
  }

So far I understand that I need to put the deletion date and just edit rather than delete, but I did not really understand how it works. Could anyone help me?

    
asked by anonymous 22.04.2017 / 18:13

1 answer

3

Logical Exclusion is a practice to prevent data loss. Instead of deleting the bank record, you flag in a field that record is deleted.

One thing to consider is that PHP itself does not change the database, it just sends string-shaped SQL commands for the DBMS to execute.

Example

You can create a " deleted " column of type timestamp. Instead of deleting the record, just update this column with the current timestamp.

See the example in PHP / MySQL:

$sql = "UPDATE $table SET deletado=NOW() WHERE id = $id";

This command will update the 'deleted' field of the registry with a timestamp. The MySQL NOW () function returns a timestamp automatically.

From this, you will only select the records that have the null deleted field. These will be the "active" records. Example:

$sql = "SELECT * FROM $table WHERE deletado IS NULL";

When you want to return the deleted logs logically, query to select only the records where the deleted field is not null, for example:

$sql = "SELECT * FROM $table WHERE deletado IS NOT NULL";

To "reactivate" a record, update the deleted field to NULL:

$sql = "UPDATE $table SET deletado = NULL WHERE id = $id";
    
22.04.2017 / 23:55