1,105,578 Community Members

Protecting Against SQL Injection Help

Member Avatar
Octet
Posting Pro
579 posts since Nov 2011
Reputation Points: 45 [?]
Q&As Helped to Solve: 53 [?]
Skill Endorsements: 16 [?]
Featured
Sponsor
 
0
 

I am currently using MySQL so people can send my a message that shall be stored in the database.
The only issue is I have no idea how to protect against SQL Injection, below is my HTML:

<form action="Action.php" method="POST" />

	<p>Name: <input type="text" name="Name" /> </p>
	<p>Comment: <input type="text" name="Comment" /> </p>
	<p>Email: <input type="text" name="Email" /> </p>
	<input type="submit" value="SUBMIT" />
</form>

And here is my PHP file:

<?php

define('DB_NAME', 'Database');
define('DB_USER', 'root');
define('DB_PASSWORD', 'GP6G9gb5F5');
define('DB_HOST', 'localhost');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);


if (!$link) {

	die('Could not connect');
}

$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected){
	die('Could not connect');
}

$value = $_POST['Name'];
$value2 = $_POST['Comment'];
$value3 = $_POST['Email'];

$sql = "INSERT INTO Contact (Name, Comment, Email) VALUES ('$value', '$value2', '$value3')";

if (!mysql_query($sql)) {
	die('Could not connect');
}

mysql_close();

?>

Connected!

These files are just a quick test, before I add them to my actual site. Please could someone tell me how, or if I need to add something in to prevent against SQL Injection?


Thank you

Member Avatar
BenzZz
Junior Poster
119 posts since Feb 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 6 [?]
Skill Endorsements: 0 [?]
 
0
 

You could use the filter_var function... http://php.net/manual/en/function.filter-var.php.

It can take different filters as parameters in order to sanitise the variable in the way you want to.

An example for your name variable is:

$value = filter_var($_POST['Name'], FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);

The sanitisation of the string along with the filter to allow no encode quotes prevents sql injection.

Member Avatar
diafol
Where are my eyes?
12,977 posts since Oct 2006
Reputation Points: 1,821 [?]
Q&As Helped to Solve: 1,848 [?]
Skill Endorsements: 92 [?]
Moderator
Featured
Sponsor
 
0
 

You may be better off using PDO and prepared statements.

Question Answered as of 1 Year Ago by diafol and BenzZz
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: