using _GET url link to delete a record from mysql

2019-07-29 07:28发布

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.

3条回答
混吃等死
2楼-- · 2019-07-29 08:10

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.

查看更多
做个烂人
3楼-- · 2019-07-29 08:25
<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.

查看更多
祖国的老花朵
4楼-- · 2019-07-29 08:27

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']))
查看更多
登录 后发表回答