Search code examples
phpbuttonpostsspl

Delete button after every post (php, sql)


I need some help with PHP and SQL. Im doing a website where you can post notes in different subjects (Work, Home, School, and so on). After every note that being selected from my database I want a button that can delete that specific post when it's not needed anymore. I can make it delete but is deletes wrong note, always the one above or below. I don't know whats wrong with my code? Please help me.

    <?php 
    $query = "SELECT * FROM notes WHERE subject='Work' order by id desc";
    $result = mysql_query($query);
    while ($row = mysql_fetch_array($result)) { 
            $id = $row['id'];
            $subject = $row['subject'];
            $date = $row['date'];
            $note = $row['note']; 

            print "<p><strong>$subject</strong> ($id), $date </p>"; 
            print "<p> $note </p>";

        ?>
        //delete button starts here here
        <form id="delete" method="post" action="">
        <input type="submit" name="delete" value="Delete!"/>    
        <?php
        if(isset($_POST['delete'])){
           $query = "DELETE FROM notes WHERE id=$id"; 
           $result = mysql_query($query);
        }
        ?>  
        </form>
        <?php
    }   
    ?>

And when I press delete I get this:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/mirho663/www-pub/webbpage/menu2.php on line 40

What does that mean and how do I fix it?


Solution

  • I updated your script below, try it if it works.

    <?php 
    
        if(isset($_POST['delete'])){
           $id = $_POST['delete_rec_id'];  
           $query = "DELETE FROM notes WHERE id=$id"; 
           $result = mysql_query($query);
        }
    
        $query = "SELECT * FROM notes WHERE subject='Work' order by id desc";
        $result = mysql_query($query);
        while ($row = mysql_fetch_array($result)) { 
                $id = $row['id'];
                $subject = $row['subject'];
                $date = $row['date'];
                $note = $row['note']; 
    
                print "<p><strong>$subject</strong> ($id), $date </p>"; 
                print "<p> $note </p>";
    
            ?>
            //delete button starts here here
            <form id="delete" method="post" action="">
            <input type="hidden" name="delete_rec_id" value="<?php print $id; ?>"/> 
            <input type="submit" name="delete" value="Delete!"/>    
    
            </form>
            <?php
        }   
        ?>