jsuke06
jsuke06

Reputation: 145

trying to DELETE a row with PHP and MYSQL

I'm trying to add a delete button to a PHP and MYSQL to-do list. I test my query without placeholders in mysql workbench and the delete query works fine. I'm also pretty sure the variables I sent to the url work too, when I hover over them in my page I can see the values are correct. When I execute delete link, nothing happens and I don't get any error messages. Not sure what I'm doing wrong. Any help is appreciated

<?php
require_once 'app/init.php';

if($_GET['delete']){

   $id =  $_GET['id'];
   

    $deleteQuery = $db->prepare("
    DELETE 
    FROM todo_list
    WHERE id = :id
    AND user = :user LIMIT 1
    ");

    $deleteQuery->execute([
        'id' => $id,
        'user' => $_SESSION['user_id']
    ]);

}

header('Location: index.php');
?>

this is where the variables are coming from

<section>
        <div class="container">
            <div class="list">
                <h1 class="header">To Do</h1>

                <?php if(!empty($items)) : ?>
                <ul class="items">
                    <?php foreach($items as $item): ?>
                    <li>
                        <span class="item<?php echo $item['done'] ? ' done': '' ?> "><?php echo $item['name']; ?></span>
                        <?php if(!$item['done']): ?>
                        <a href="mark.php?as=done&item=<?php echo $item['id']; ?>" class="done-button">Mark as Done</a>
                        <a href="delete.php?delete=true&item=<?php echo $item['id']?>" class="item-delete">Delete <i class="fas fa-trash-alt"></i></a>
                        <?php endif; ?>
                    </li>
                    
                  
                    <?php endforeach; ?>
                </ul>
                <?php else:?>
                        <p>you haven't added anything yet</p>
                <?php endif; ?>
                <form class="item-add" action="add.php" method="post">
                    <input type="text" name="name" placeholder="type a new item" class="input" autocomplete="off" required>
                    <input type="submit" value="Add" class="submit">

                </form>
                
            </div>
        </div>
    </section>

Upvotes: 1

Views: 88

Answers (3)

Ariful Islam
Ariful Islam

Reputation: 893

In your attribute tag you are using item as query string .

<a href="mark.php?as=done&item=<?php echo $item['id']; ?>

But you are getting data with wrong query string id. You should use below one.

if($_GET['delete']){

   $id =  $_GET['item'];

Upvotes: 0

Jesse de Boer
Jesse de Boer

Reputation: 92

You probably need to check if the get isset if(isset($_GET['item'])) { var_dump($_GET['item']); }

Upvotes: 1

ArSeN
ArSeN

Reputation: 5248

You called the parameter item and not id.

$id =  $_GET['id'];

should hence be

$id =  $_GET['item'];

Upvotes: 3

Related Questions