How to delete line in Mysql and php

Asked

Viewed 278 times

0

Can someone help me? I’m a beginner in programming and I’m not being able to delete, through a button, no line in the database by ID. I have tried to solve several ways but it simply assumes that everything is correct but does not erase the line defined in the database.

Follows the code:

<?php 
include_once 'includes/dbh.inc.php';
$sql = "SELECT * FROM novidades ORDER BY idGallery DESC LIMIT 1";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "SQL statement failed";

} else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while($row = mysqli_fetch_assoc($result)){
$idfinal = $row['idGallery'];

echo'
<div class="single-table">
<div class="table-responsive">
<table class="table table-hover text-center">
<thead class="text-uppercase">
<tr>
   <th scope="col">Post nº</th>
   <th scope="col">Título</th>
   <th scope="col">Descrição</th>

   <th scope="col">Editar / Apagar</th>
</tr>
</thead>
<tbody>
<tr>

   <th scope="row">'.$row["idGallery"].'</th>
   <td>'.$row["titleGallery"].'</td>
   <td>'.$row["descGallery"].'</td>';  }}?>

The button:

 <?php
    if(isset($_POST['apagar'])){
    echo('
    <h5 class="header-title">Tem a certeza que deseja eliminar este post?</h4>
    <form action="includes/novidades-delete.inc.php" method="POST">
    <button name="delete" type="submit" class="btn btn-danger btn-lg btn-block">Eliminar post</button></form>');
        }else{
        echo "";

        }

        ?>

And the new code-delete.inc.php:

<?php

if(isset($_POST['delete'])){
    include_once "dbh.inc.php";
  $id = $_POST['idGallery'];
    $sql = "DELETE FROM novidades WHERE idGallery='$id'";
    $result = mysqli_query($conn, $sql);
    if(!$result){
    die("Falha ao executar o comando: " . mysqli_error($conn));}
  else{

    header ("Location:/winjoy3/admin/novidades-deleted.php?idGallery=$id");
}}
?>
  • 1

    Where are you sending the idGallery in the form that calls the novidades-delete.inc.php?

  • Ahhhh, you got it!! Just add <input type="Hidden" name="ids" value="'. $Row["idGallery"]. '"/> and change to $id = $_POST['ids']; Thank you very much!! :)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.