0

I have the following PHP:

<?php

	define('DB_NAME', 'database');
	define('DB_USER', 'root');
	define('DB_PASSWORD', 'password');
	define('DB_HOST', 'localhost');

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

	if (!link){
		die('Could not connect to database');
	}

	$db_selected = mysql_select_db(DB_NAME, $link);

	if (!$db_selected) {
		die('Could not connect to the database');
	}

	$value = htmlspecialchars($_POST['Name']);
	$value2 = htmlspecialchars($_POST['Email']);
	$value3 = htmlspecialchars($_POST['Subject']);
	$value4 = htmlspecialchars($_POST['Message']);

	$sql = "INSERT INTO Private_Message (Name, Email, Subject, Message) VALUES ('$value', '$value2', 	'$value3', '$value4')";

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

	mysql_close();

	header( 'Location: contact.php' ) ;
?>

and the following form:

<form action="Action.php" method="POST" />
				<p>Name (any name you would like me to refer to you as): <input type="text" 					name="Name" /> </p>
				<p>Email (must be valid, in order to recieve a reply): <input type="text" 					name="Email" /> </p>
				<p>Subject (this could be something like, Technical Issues): <input type="text" 				name="Subject" /> </p>
				<textarea rows="10" cols="50" name="Message">Your Message Goes Here: </textarea>
				<input type="submit" value="SUBMIT" />
			</form>

I have attempted to prevent SQL injection by using, "htmlspecialchars" but I am not sure if I have used them correctly and equally I don't know how much protection this will offer?

Could someone please suggest to me how I could further protect against SQL Injection?

2
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by Octet
1

You need to use mysql_real_escape_string

$value = htmlspecialchars(mysql_real_escape_string($_POST['Name']));
0

You need to use mysql_real_escape_string

$value = htmlspecialchars(mysql_real_escape_string($_POST['Name']));

Thank you so much! It works perfectly, just tried sending myself a message using 'forbidden characters' and it works!
Although this won't prevent all SQL attacks, it sure shall help!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.