We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,527 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Protecting Against SQL Injection Help

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

3
Contributors
2
Replies
5 Hours
Discussion Span
1 Year Ago
Last Updated
4
Views
Question
Answered
AHarrisGsy
Posting Pro in Training
455 posts since Nov 2011
Reputation Points: 48
Solved Threads: 33
Skill Endorsements: 13

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.

BenzZz
Junior Poster
119 posts since Feb 2011
Reputation Points: 10
Solved Threads: 6
Skill Endorsements: 0

You may be better off using PDO and prepared statements.

diafol
Keep Smiling
Moderator
10,609 posts since Oct 2006
Reputation Points: 1,628
Solved Threads: 1,506
Skill Endorsements: 57
Question Answered as of 9 Months Ago by diafol and BenzZz

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0625 seconds using 2.66MB