Search code examples
phpdatabasefunctionif-statementdelete-row

Delete from html table made by database PHP


Here is the table below that I'm trying to delete rows out of:

<form method="POST" >
        <table class="sortable">
            <thead>
                <tr>
                    <th id="makehead">Make </th>
                    <th id="modelhead">Model </th>
                    <th id="idhead">Delete </th>
                </tr>
            </thead>
            <tbody>
                <?php
                $i = 0;

                foreach ($carArray as $k => $carInfo) {
                    $i++;
                    echo '<tr>';
                    if ($i % 2) {
                        echo '<td class="make">' . $carInfo['make'] . '</td>
                              <td class="model">' . $carInfo['model'] . '</td>
                              <td class="id"><input type="checkbox" name="id" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
                    } else {
                        echo '<td class="makelight">' . $carInfo['make'] . '</td>
                              <td class="modellight">' . $carInfo['model'] . '</td>
                              <td class="idlight"><input type="checkbox" name="id" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
                    }
                }
                ?>
                </tr>

        </table>

    </tbody>
    <td>
        <input Onclick="return ConfirmDelete();" name="delete" type="submit" id="delete" value="Delete"></input>
    </td>
</table></form>

As you can see i'm using checkboxes to tick each row then the delete button will have a confirm message then should delete but it doesn't here is my if statement:

if ($_REQUEST['delete']) {
        $dbid = $_REQUEST['id'];
        $db->setdbid($dbid);

So when this wasn't working I had a look on here and on other questions people said I need a setter function so i did this: EDIT: this is my class file.

public function setdbid($dbid){
    $this->dbid=$dbid;
}

for this main function to delete things:

 public function delete($dbid) {
    try {
        $sql = "DELETE FROM cars WHERE id = '$dbid'";
        $this->db->exec($sql);

        echo "Car has been deleted.";
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

So that's all the relevant code I think, please help me if you can.


Solution

  • You just have to replace some piece of code in PHP :

    if ($_REQUEST['delete']) {
        $dbid = $_REQUEST['id'];
        $db->delete($dbid); //Assuming delete is well a $db method, else replace it by the correct delete call
    }