Nicholas Nicolaou
Nicholas Nicolaou

Reputation: 5

DELETE link does nothing in PHP when removing data from PHPMyAdmin

I have created a table in PHPMyAdmin, and I have connected to it via a localhost. My PHP code displays the data in a table.

I want to be able to delete a certain row, so I created a html/php link to delete the row within a table.

My problem is that whenever I press delete, the page just refreshes without an error but the record is still there.

Is there something missing within my code?

<?php
    // Connect to the database
    $username="root";$password="test";$database="products";

    // Connect to the MySQL server and select the required database
    $connection = new mysqli("localhost",$username,$password, $database);

    $sql = "";

    $sql = "SELECT * FROM products";

    $ID = isset($row['ID']) ? $row['ID'] : '';{
    $query = mysqli_query($connection, "DELETE FROM products WHERE ID=$ID");
    }

    $result = $connection->query($sql);

    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo "<tr>\n";
            echo "<td>" . $row['Name'] . "</td>\n";
            echo "<td>" . $row['Description'] . "</td>\n";
            echo "<td>" . $row['Price'] . "</td>\n";
            echo "<td>" . $row['Cost_Price'] . "</td>\n";
            echo "<td>" . $row['Stock'] . "</td>\n";
            echo "<td>" . $row['EAN'] . "</td>\n";
            ?>
            <td><a href="?mode=delete&ID=<?php echo $row["ID"]; ?>"
               title="Delete <?php echo $row["ID"]; ?>">Delete</a></td>
            <?php

            echo "</tr>\n";
        }
    }

$stmt = $connection->prepare('SELECT * FROM products WHERE name = ?');
$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();

$connection->close();

?>

Upvotes: 1

Views: 371

Answers (1)

Nana Partykar
Nana Partykar

Reputation: 10548

Change

$ID = isset($row['ID']) ? $row['ID'] : '';{
$query = mysqli_query($connection, "DELETE FROM products WHERE ID=$ID");
}

To

if(isset($_GET['ID']) && ($_GET['mode'] == 'delete')) {
  $ID = $_GET['ID'];
  $query = mysqli_query($connection, "DELETE FROM products WHERE ID=$ID");
}

Explanations

When after clicking delete link, it comes to this line

$ID = isset($row['ID']) ? $row['ID'] : '';{.

Here, $row['ID'] is not set. So, $ID set to "" as you declared in your code. So, DELETE statement is not able to find that product which you wanted to delete.

Actually, in delete link. You are passing 2 variables. One is mode and other is ID of product. Catch those 2 variables through $_GET as I mentioned in my answer.

Quick Links

  1. How to set $_GET variable
  2. $_GET : PHP Manual

Upvotes: 2

Related Questions