0% found this document useful (0 votes)
22 views3 pages

3.PHP Delete A Record From A Table From A Database

This document describes how to delete records from a MySQL database table using PHP. It involves creating a page to display a list of records with delete links, and a separate page to handle the delete action. The delete page checks the request, connects to the database, constructs a DELETE query with the record ID, executes it, and confirms whether the record was deleted.

Uploaded by

Fide Ben Slimen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views3 pages

3.PHP Delete A Record From A Table From A Database

This document describes how to delete records from a MySQL database table using PHP. It involves creating a page to display a list of records with delete links, and a separate page to handle the delete action. The delete page checks the request, connects to the database, constructs a DELETE query with the record ID, executes it, and confirms whether the record was deleted.

Uploaded by

Fide Ben Slimen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

3) PHP – Delete a record from a table from a

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.

Create a list to visualize the records with a “link to delete”

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");

/* verifica se ocorreu algum erro na ligação */


if ($ligacao->connect_errno) {
echo "Falha na ligação: " . $ligacao->connect_error;
exit();
}

/* definir o charset utilizado na ligação */


$ligacao->set_charset("utf8");

/* texto sql da consulta*/


$consulta = 'SELECT * FROM departamento';

/* executar a consulta e testar se ocorreu erro */


if (!$resultado = $ligacao->query($consulta)) {
echo ' Falha na consulta: '. $ligacao->error;
$ligacao->close(); /* fechar a ligação */
exit();
}

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');

/* validar os dados recebidos através do pedido */


if (empty($id) || $operacao!="eliminar"){
echo " Erro, pedido inválido ";
exit();
}
}
else{
echo " Erro, pedido inválido ";
exit();
}

/* estabelece a ligação à base de dados */


$ligacao = new mysqli("localhost", "root", "", "empresa");

/* verifica se ocorreu algum erro na ligação */


if ($ligacao->connect_errno) {
echo "Falha na ligação: " . $ligacao->connect_error;
exit();
}

/* texto sql da consulta*/


$consulta = "DELETE FROM departamento WHERE id = '$id' ";

/* executar a consulta e testar se ocorreu erro */


if (!$ligacao->query($consulta)) {
echo " Falha ao executar a consulta: \"$consulta\" <br>" . $ligacao->error;
$ligacao->close(); /* fechar a ligação */
echo ' <br> <a href="departamentos.php"> voltar </a>' ;
exit();
}

/* verificar o resultado da consulta */


if($ligacao->affected_rows > 0){
echo " O registo com o id = $id foi eliminado com sucesso" ;
$ligacao->close(); /* fechar a ligação */
echo '<br> <a href="departamentos.php"> Voltar </a>' ;
}
else{
header("Location: listardepartamentos.php");
echo " O registo com o id = $id não encontrado!" ;
$ligacao->close(); /* fechar a ligação */
echo '<br> <a href="departamentos.php"> voltar </a>' ;
}

You might also like