"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Properly Delete Multiple Database Rows Using Checkboxes in PHP?

How to Properly Delete Multiple Database Rows Using Checkboxes in PHP?

Published on 2024-11-19
Browse:402

How to Properly Delete Multiple Database Rows Using Checkboxes in PHP?

Collaboratively Deleting Database Rows with Checkboxes in PHP

Faced with the task of purging multiple rows from your MySQL stronghold, you've sought enlightenment in the depths of coding wisdom. While embarking on this data-cleansing endeavor, you've seemingly run into an insurmountable roadblock.

The code you've crafted, though valiant in intent, fails to execute its intended purpose of row annihilation. Determined to overcome this obstacle, you seek guidance by presenting your code to the esteemed coding community:

// PHP witchcraft to connect to MySQL
$dbc = mysqli_connect('localhost', 'root', 'admin', 'sample') or die('MySQL is out to get you!');
$query = "select * from links ORDER BY link_id";
$result = mysqli_query($dbc, $query) or die('Whoops! Query went awry!');
$count = mysqli_num_rows($result);
// Assemble your army of checkboxes
while ($row = mysqli_fetch_array($result)) {
    echo 
    
    $row[link_id]
    $row[link_name]
    $row[link_url]

HTML;
}
// The arsenal of deletion awaits your command
if (isset($_POST['delete'])) {
    // Retrieve your checked victims
    $checkbox = $_POST['checkbox'];

    // Summon the wrath of deletion upon each victim
    foreach ($checkbox as $del_id) {
        $sql = "DELETE FROM links WHERE link_id='$del_id'";
        // Unleash the purging power!
        $result = mysqli_query($dbc, $sql);
    }

    // If successful, redirect to the crime scene
    if ($result) {
        echo '';
    }
}

The Sage's Solution

Alas, your code falters due to a few critical oversights:

  1. Array or Single: Your checkbox input tags lack the [] suffix to treat them as an array. Without it, PHP won't recognize multiple selections correctly. Use name="checkbox[]".
  2. Database Summoning: Your query execution line was missing the connection variable. It should be $result = mysqli_query($dbc, $sql);.

With those rectifications, your code shall banish rows like a digital sorcerer. Embark on your data-cleansing quest with renewed confidence!

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3