Skip to content
Advertisement

Delete MYSQL DB Entry via PHP / HTML Button

Hey.

Iam learning PHP and MYSQL atm.

So i wrote already code which will display everything from my database nicely into HTML. I create also a button which says Delete.

Now i want to write a Code which actually Deletes the specific entry (all have an ID ) but iam kinda lost. i know the command is: $sql = “DELETE FROM cars WHERE car_id=’$car_id'”; but how can i add this event in php to the button click.

I thought in the generating code i add the car id to the button with <button id=”‘.$row[“car_id”.’“> and then somehow magically delete the entry when i click the button but iam stuck & lost in how to call it.

<?php
$servername = "localhost";
$username   = "root";
$password   = "";
$dbname     = "muscle_cars";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
   die("Connection failed: " . mysqli_connect_error() . "n");
}

$sql = "SELECT car_id, carname, hp, img, available FROM cars";
$result = mysqli_query($conn, $sql);
// fetch the next row (as long as there are any) into $row
while($row = mysqli_fetch_assoc($result)) {
     
    
echo '
<div class="card col-3 m-3 bg-info" >
  <img src="'.$row["img"].'" class="card-img-top" alt="...">
  <div class="card-body">
    <h5 class="card-title">'.$row["carname"].'</h5>
    <p class="card-text">Horsepower : '.$row["hp"].'</p>
    <p class="card-text">Available : '.$row["available"].'</p>

    <a href="#" class="btn btn-outline-danger text-white">DELETE</a>
  </div>
</div>
';
}

// Free result set
mysqli_free_result($result);
// Close connection
mysqli_close($conn);
?>

Advertisement

Answer

You can use form with action button name to identify what part of action to do

    <?php
      
        if(isset($_POST['delete_rows'])) { //<-- see input name
            ... delete anything from database ...
        } else
        if(isset($_POST['select_rows'])) { //<-- see input name
            ... select anything from database ...
        } 
    ?> 
      
    <form method="post"> 
        <input type="submit" name="delete_rows" value="Delete"/>
        <input type="submit" name="select_rows" value="Select"/>
    </form>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement