prevent sql injection on form submit

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Lphp
Forum Commoner
Posts: 74
Joined: Sun Jun 26, 2011 9:56 pm

prevent sql injection on form submit

Post by Lphp »

I have a long form , if I want every input fields can prevent sql injection on form submit
how to do that :?
Gopesh
Forum Contributor
Posts: 143
Joined: Fri Dec 24, 2010 12:48 am
Location: India

Re: prevent sql injection on form submit

Post by Gopesh »

Use mysql_real_escape_string() to prevent sql injection.

Code: Select all

<?php
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
?>
Check http://www.digifuzz.net/archives/2007/0 ... -with-php/ .
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: prevent sql injection on form submit

Post by Celauran »

In addition to escaping the values, make sure the data you're getting matches what you're expecting. If you expect a field to contain only numbers, there's no point escaping it if it contains letters; you already know it's junk data and should return an error. Also, at the very least, use mysqli.
User avatar
egg82
Forum Contributor
Posts: 156
Joined: Sat Oct 01, 2011 9:29 pm
Location: Colorado, USA

Re: prevent sql injection on form submit

Post by egg82 »

Code: Select all

$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$result = mysql_query("SELECT * FROM `accounts` WHERE `username`='".mysql_real_escape_string($username)."' AND `password`='".mysql_real_escape_string($password)."'");
if(!$result){
	echo(mysql_error());
	exit();
}
Lphp
Forum Commoner
Posts: 74
Joined: Sun Jun 26, 2011 9:56 pm

Re: prevent sql injection on form submit

Post by Lphp »

thank you for all the replies
I looking for a loop to take care all the values on form , I don't want to handle it one by one
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: prevent sql injection on form submit

Post by social_experiment »

Lphp wrote:I looking for a loop to take care all the values on form , I don't want to handle it one by one
You could make an array of all the input fields and pass that to a function that wraps each in a function like mysqli_real_escape_string(), and add that value back into an 'escaped' array.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply