简体   繁体   中英

deleting rows in mysql table with php

new to PHP here I have a page that loops through a DB and displays the contents of the table. When the delete button is pressed I would like to delete that entry in the DB. Right now when the button is pressed and the page goes to delete.php I keep getting Undefined index: userid

Here is the first page:

<?php
foreach($rows as $row){
$userid = $row['userid'];
$pName = $row['pName'];
$pDesc = $row['pDesc'];
$dDate = $row['dDate'];
?>

<div class="project-container">

    <label>Project ID:</label>
    <span><?php echo $userid; ?></span><br>
    <label>Project Owner:</label>
    <span><?php echo $pName; ?></span><br>
    <label>Project Description:</label>
    <span><?php echo $pDesc; ?> </span><br>
    <label>Project Due Date:</label>
    <span><?php echo $dDate; ?> </span><br>
    <br>

    <form action="#" method="GET">
        <input type="submit" name="delete" value="Delete Project">
    </form>
    <form action="index.php">
        <input type="submit" name="update" value="Update Project">
    </form>
    </div>
    <br>
    <br>

</div><br><br><?php } ?>

and this is delete.php:

include('connect.php');
$userid = $_GET['userid'];
echo $userid;
$sql = "DELETE FROM projecttable WHERE userid  = '$userid'";
$conn->exec($sql);

Any help is appreciated, thank you

Try this. It will send a variable in the GET array named userid with the userid value to delete.php:

<form action="delete.php" method="GET">
    <input type="hidden" name="userid" value="<?php echo $userid; ?>">
    <input type="submit" name="delete" value="Delete Project">
</form>

The action attribute in the form tag will direct where to sent the request which is the delete.php script and the method will tell it to use the GET array which basically puts the keys and values in the URL itself. You could alternately do this by modifying the action field instead of using an input field. I just like this way for readability.

Because input fields are usually visible, using a hidden field prevents it from being displayed on the web page, but it's easy to manage in the code. The name attribute of the input field determines the name of the key in the GET array and the value attribute determined the value of that element in the GET array. So it ends up being $_GET['name_attribtue'] = value_attribute in your PHP script.

Just for example. If you changed the form method attribute to POST, your PHP script would need to use the $_POST array instead of the $_GET array.

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