0

I am pretty new to mysql and php and I am trying to set up some parameters to help me delete an entry from a table if the user presses the delete button. I currently have it set up to where the user can search the table by using department, name, or course number. Each delete statement is prepared by which search they are using.

enter image description here

The issue I am running into, is that when I create my delete statements, I do not know how to determine which the data being selected by the SELECT statement. A short snippet of code is displayed below.

if($_POST['radios'] == 0){
    $sql = "SELECT * FROM classes where department LIKE '" . $_POST['search'] . "%';";
$select = 0;
$id = $sql;//problem area. Can't figure out how to pass the needed deparment info.

if($_POST['submit'] == "delete"){
  if($select == 0){
  mysqli_query($mysqli, "DELETE FROM classes WHERE department='".$id."'"); //need $id to match the correct department from table
  mysqli_close($mysqli);
  }

Edit: table

DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes` (
`name` varchar(255),
`department` varchar(255),
`course_id` varchar(255),
PRIMARY KEY(`course_id`),
`start` time,
`end` time,
`days` varchar(255)
);

Thanks for the help!

Dan O
  • 6,022
  • 2
  • 32
  • 50

1 Answers1

0

Here's one simple way to delete a particular "class".

Treat your buttons like a link such that when you click on it, it redirects to a particular page e.g. page.php?delete=ID.

I am assuming you are dynamically generating the table, so your code would be somewhat similar to

<?php foreach ($classes as $class) : ?>
    <tr>
        <td><?= $class->name ?></td>
        <td><?= $class->department ?></td>
        <td><?= $class->course_id ?></td>
        <td><?= $class->start ?></td>
        <td><?= $class->end ?></td>
        <td><?= $class->days ?></td>
        <!-- note the use of type="button" as we don't want to submit anything -->
        <!-- window.location.href is to redirect -->
        <td><button type="button" onclick="window.location.href='page.php?delete=<?= $class->course_id ?>'">delete</button></td>
        <td><button type="button">update</button></td>
    </tr>
<?php endforeach ?>

Then in your processing script i.e. page.php, you would do

if ($_POST['radios'] == 0){
    $sql = "SELECT * FROM classes where department LIKE '" . $_POST['search'] . "%';";
    // etc
}

// note we are using a GET method as we only did a redirection
if (!empty($_GET['delete'])) {
    $id = $_GET['delete'];
    mysqli_query($mysqli, "DELETE FROM classes WHERE course_id='".$id."'");
    mysqli_close($mysqli);
    // good idea to go back to previous page to see changes
    header('Location: previousPage.php');
    exit;
}

That's it.

Side-remark: Please please please read Lee Taylor's comment about SQL injection as this code is vulnerable to it. Start learning about prepared statements.

Community
  • 1
  • 1
Mikey
  • 6,728
  • 4
  • 22
  • 45