/    Sign up×
Community /Pin to ProfileBookmark

SQL Security (Inject) but allow email

I have an website and really want to prevent all SQL injections BUT allow emails in a string that must go into the database as text. How can I do this?

>

Mr C

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@itsmrcauthorAug 31.2008 — Forgot to say, I'm using MySQL and PHP
Copy linkTweet thisAlerts:
@roscorAug 31.2008 — Firstly ensure you have you mysql database correctly set up. I presume you are getting the email address from a form, if so use

preg match perhaps something like the following, n.b. there are many other examples out there,
[code=php]if(preg_match('/^[w]+[-w._]*@[w]+[-w]+(.[w]+[-w]+)*.[w]{2,6}$/ ', $_POST['email'])){
$email = $_POST['email'];
}
else {
$error1 .= "Required!";
$vaild1 = "Email not valid format!";
$errcount++;

}[/code]

Then for the insert to prevent sql injection use mysql real escape string

[code=php]
// contains databse connect info
include("dbconninfo.php");

//connect to database
mysql_connect($host,$username,$password);
@mysql_select_db($database) or die(mysql_error());

//Insert to the databse
$query = "INSERT INTO mytable VALUES ('','$email'";
mysql_query($query);

//use mysql real escape string after the connection is made
$email = mysql_real_escape_string($_POST['email']);
[/code]

then isn the form remember set the action to parse the page then echo out any errors from the preg_match with the error1
[code=php]
<!--this form uses a file upload hence the multipart/form-data other wise omit the enctype altogether -->

<form id="Upload" enctype="multipart/form-data" name="listmenu" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">[/code]
×

Success!

Help @itsmrc spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...