3.PHP Delete A Record From A Table From A Database
3.PHP Delete A Record From A Table From A Database
database
In this exercise we will describe how we can delete records from a table created in a MySQL database
using a PHP script.
In the process we will demonstrate here, to delete records from a database table, we will use the following
strategy:
1. Create the file: “lista_para_eliminar.php”, which will be responsible for displaying the list of all records
in the department table. The list will contain a link to delete each record.
2. Create the “deletedepartamento.php” file, which will be responsible for deleting the selected record
through the list of departments presented by the “listadepartamentos.php” file.
To display the list of records in a table, we will use the same process demonstrated in the article “1) PHP –
List records in a table in a MySQL database”. The difference is that we will include the code to create a
link to the page that will delete the record. The link used will identify the operation and the “id” record to
be deleted.
<?php
/* estabelece a ligação à base de dados */
$ligacao = new mysqli("localhost", "root", "", "empresa");
if($ligacao->affected_rows == 0){
echo " Não existem registos na tabela departamento ";
}
else{
/* percorrer os registos (linhas) da tabela e mostrar na página */
while ($row = $resultado->fetch_assoc()){
echo 'id: ' . $row['id'] . ' Nome: ' . $row['nome'] .
'<a href="eliminardepartamento.php?id='.$row['id'] .
'&operacao=eliminar"> - Eliminar</a><br>';
}
}
$resultado->free(); /* libertar o resultado */
$ligacao->close(); /* fechar a ligação */
In the “eliminadepartamento.php” file we will create the code to perform the following steps:
1. Check whether the request to delete and validate the data coming from the URL was sent.
2. Connect to the database and check if an error has occurred.
3. Create the query sql text, execute and check the result.
<?php
/* Verificar se foi enviado o pedido para eliminar */
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$id = filter_input(INPUT_GET, 'id');
$operacao = filter_input(INPUT_GET, 'operacao');