Deleting row from $_GET

时间:2016-07-11 23:09:00

标签: php sql

searchcars.php

echo "<a href=\"delete.php?VIN=" . $row['VIN'] . "\">Delete Car</a>";

delete.php

$VIN = $_GET['VIN'];
$sql = "DELETE FROM Cars WHERE VIN = '$VIN'";
mysql_query($sql);

If I echo $VIN; I do get the right VIN I am trying to delete. What am I missing here? Beside all the data validation and so forth. This is just a basic (for most) delete row query I am trying to execute. Thanks ahead of time.

1 个答案:

答案 0 :(得分:1)

更好,(更安全的方法)是:

PHP:searchcars.php

<?php

// Set Up MySQL Connection
$servername = "localhost";
$username = "username";
$password = "password";

try 
{
    $conn = new PDO("mysql:host=$servername;dbname=MyDB",$username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
    echo "Connection failed: " . $e->getMessage();
}
    // If $_POST['VIN'] is Set, Do a Little Validation
    if(isset($_POST['VIN']))
    {
        // If VIN Contains Any Characters other Than Numbers or Letters then Die
        if(!preg_match('/^[a-zA-Z0-9]{24}/',$_POST['VIN']))
        {
            die('A maximum combination of 24 numbers/letters is allowed');
        }
        // Delete Specified VIN Record From MySQL
        $query = "
            DELETE 
            FROM Cars
            WHERE VIN = :VIN
        ";
        try
        {
            $stmt = $conn->prepare($query);
            $stmt->bindParam(':VIN', $_POST['VIN']);
            $stmt->execute();
        }
        catch(PDOException $ex)
        { 
            die("MySQL error:" . $ex->getMessage());
        }
    }       
?>

HTML:

<form action="searchcars.php" method="POST">
    <button type="submit" name="VIN" value="<?php echo ($row['VIN']); ?>">Delete Car</button>
</form>

我建议您阅读PDO,准备好的陈述以及POST与GET ......