简体   繁体   中英

PHP Delete record from database MySql

I need to delete a record, in this case a categories from my forum, from the database based on its id.

<?php
    if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
    {
?>
    <td>
        <form method="post">
            <input type="hidden" value="<?= ['cat_id']; ?>">
            <input type="submit" name="submit" value="Remover" />
        </form>
    <?php
        if(isset($_POST['submit']))
        {
            mysql_query("DELETE FROM categories where cat_id = 'cat_id'");
        }
    ?>
    </td>
<?php
}
?>

i cant get a "good" way to do it... :(

EDIT: This is for a programming lesson not a real forum!!

Your HTML Input Field needs a name so it can be identified by your PHP. Then, in your Code Block where you attempt to delete the category, you need to acces the category id using the $_POST array.

Another thig you want to do is read up onj the dangers of SQL injections . If you're just playing around with PHP and MySQL at the moment: Go Ahead. But if you actually want to develop, maybe you should read up on a few other things as well, even if it seems like overkill at first: PHP The Right Way .

Nontheless, try this:

    <?php
        if(isset($_SESSION['signed_in']) && $_SESSION['user_level'] == 1)
        {
    ?>
        <td>
            <form method="post">
                <input type="hidden" name="hid_catid" id="hid_catid" value="<?php  echo $cat_id; ?>">
                <input type="submit" name="submit" value="Remover" />
            </form>
        <?php
            if(isset($_POST['submit']))
            {

$query = "DELETE FROM categories where cat_id = '".(int)$_POST['hid_catid']."'";
mysql_query($query);
            }
        ?>
        </td>
    <?php
    }
    ?>

--> hidden field should have name and id to use

-- Thanks

Your hidden input field needs a name to be accessable after the post. Also I am not sure if ['cat_id'] is the correcty way to reference this variable. Where does it come from?

<form method="post">
    <input type="hidden" name="cat_id" value="<?= $cat_id ?>">
    <input type="submit" name="submit" value="Remover" />
</form>

Then your query has to look like this to correctly grab the id from the post.

mysql_query("DELETE FROM categories where cat_id = " . mysql_real_escape_string($_POST['cat_id']));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM