Delete data using get url php string [closed]

2019-09-21 20:32发布

I created a page called delete.php

with the following code

<?php

require_once("database.php");
$con = mysql_connect($config["db_server"],$config["db_user"],$config["db_pass"]);
mysql_select_db($config['db_name'], $con);


// The SQL statement that deletes the record
$strSQL = "DELETE FROM records WHERE record_id = 1";
mysql_query($strSQL);

// Close the database connection
mysql_close();
?>

Now if I goto http://www.domain.com/delete.php which will will delete record id with 1 in table records.

How do I use php string so when I go to http://www.domain.com/delete.php?del?=25 it deletes record_id 25?

Thanks.

2条回答
趁早两清
2楼-- · 2019-09-21 20:55

Firstly, your url construction is incorrect. It should be:

http://www.domain.com/delete.php?del=25

Then you can use del via GET to access the value:

 $del_id = $_GET['del'];
 $strSQL = "DELETE FROM records WHERE record_id = $del_id";

mysql_ is deprecated. You should be using mysqli_ or (even better) PDO instead.

The above code is susceptible to whats known as mysql injection.

As a rule of thumb, never ever trust the data coming from the user. So what you're doing here is without exaggeration disastrous.

Example:

//GET value: dave
query = " SELECT username, password FROM users WHERE username=$name ";
//Translates to:
query = " SELECT username, password FROM users WHERE username='dave' ";


//malicious input
//GET value: 'OR'1
query = " SELECT username, password FROM users WHERE username=$name ";
//Translates to:
query = "SELECT username, password FROM users WHERE username=''OR'1' ";

The nasty thing here is, 1 evaluates to true thus returning all usernames and passwords in the users table!

mysqli_real_escape_string() to the rescue

Despite being a mouthful to say, this function provides a safeguard by escaping injection attempts with MySQL-friendly '\' quote.

So pumping all your GET/POST data through this function provides a layer of security.

$name = mysqli_real_escape_string($_POST['username'];

Now hopefully that makes sense. Despite rhapsodising mysqli_real_escape_string() I would highly recommend (at some point) looking into using something a bit more sophisticated like PDO instead.

查看更多
疯言疯语
3楼-- · 2019-09-21 21:04

You would use the $_GET superglobal to capture the passed variable.

$deleteId = $_GET['del'];
$strSQL = "DELETE FROM records WHERE record_id = $deleteId";

However, this is insecure and wrong. Do not use this code!

You will need to stop using mysql_ functions (they are deprecated) and use prepared statements to help prevent SQL injection.

As mentioned in the comments, this method is not suggested due to possible issues with web spiders. This article discusses that issue and this question discusses the best practices.

查看更多
登录 后发表回答