using _GET url link to delete a record from mysql

2019-07-29 07:52发布

问题:

EDIT

Thanks for the help so far. I have edited my post to reflect the changes suggested below. I am using PDO for my database connection. The code I have now is as follows:

HTML

<a href="includes/delete-customer.php?userID='.$row->customer_id.'">

PHP

    <?php

    //MySQL Database Connect
    include 'includes/config.php';

        // confirm that the 'id' variable has been set
        if (isset($_GET['userID']) && is_numeric($_GET['userID']))
        {
                // get the 'id' variable from the URL
                $id = $_GET['userID'];

                /* Delete row from the customer table */
                $id = $dbh->exec("DELETE FROM customer WHERE customer_id = '$id'");

                $stmt->execute();
        }
?>

config.php

<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'user';

/*** mysql password ***/
$password = 'password';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=testDB", $username, $password);
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?>

I'm pretty sure the HTML is correct now and the issue lies with the delete-customer.php file. I am currently receiving the following error: Fatal error: Call to a member function exec() on a non-object

I'm not sure of how to implement the PDO query correctly. Any further advice is much appreciated.

回答1:

Your HTML section says:

<a href="includes/delete-customer.php?customer_id=$id['.$row->customer_id.']">

Is this your exact HTML syntax? This argument should be the actual numerical id, i.e. --

<a href="includes/delete-customer.php?customer_id=3">

-- either by echoing $row->customer_id (assuming it exists), or some other method of knowing that user id.

Your HTML only needs to send the actual data, not any sort of variable syntax. Your receiving PHP ($_GET['customer_id']) will interpret that for you and properly pass that to MySQL.



回答2:

Your URL passes userID as the get parameter, yet in your php script you're trying to access customer_id. Try changing your code to retrieve userID and it should work

if (isset($_GET['userID']) && is_numeric($_GET['userID']))


回答3:

<a href="includes/delete-customer.php?customer_id=<?php echo $id[$row->customer_id]; ?>">

assuming $id[$row->customer_id] is valid.

Plus, you really shouldn't delete from database on get var unless you're doing some admin validation / access rules and guarantee you don't have anyone on the job who will go rogue and manually type in numbers there.. That's just plain crazy.