php sql delete button

2019-04-14 16:31发布

问题:

I'm trying to make a delete button from sql. I started a function called $del but I don't know how to complete it, in the form of a delete button echoe'd out beside the current echo statements.

$con = mysql_connect("localhost", "user", "pass");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("database", $con);
$sql = "INSERT INTO camps (city, map, park, day, details) 
    VALUES ('$_POST[city]','$_POST[map]','$_POST[park]','$_POST[day]','$_POST[details]')";

if (!mysql_query($sql, $con)) {
    die('Error: ' . mysql_error());
}

$number = 0;
$del = mysql_query("DELETE FROM camps WHERE user_id= '$number'");

$result = mysql_query("SELECT * FROM camps");

while ($row = mysql_fetch_array($result)) {
    echo "<a href=\"'" . $row['map'] . "\">" . $row['city'] . "</a>";
    echo "<br />";
}

回答1:

You will need to make your links pass a param to a script that will delete that record. Your links would looks something like this

 echo "<a href=\"'delete.php?id=" . $user_id"\">" . $row['city'] . "</a>";

Then your delete can just grab the params from the $_GET gloabal, and pass them into your sql like so

  $del = mysql_query("DELETE FROM camps WHERE user_id=" . $_GET['user_id']);

This current query will delete all camps for that user (adjust params / sql as needbe).

However, you should NEVER pass user vars into your sql strings. You leave yourself open for sql injection attacks. I would recommend using PDO to escape your sql. I would also recommend using the post method for any destructive db operation so that you don't accidentally alter something.