/    Sign up×
Community /Pin to ProfileBookmark

Insert form values into table

Hey guys,

I’m not great at PHP, but learning. I want to simply insert values passed by a form into a mySQL table. This is the code I have so far:

[code=php]$email = $_POST[’email’];
$first_name = $_POST[‘first_name’];
$last_name = $_POST[‘last_name’];
$gender = $_POST[‘gender’];

if(!$email == “” && (!strstr($email,”@”) || !strstr($email,”.”))) {
die (“Missing or invalid email address. Please go back and fill this out again.”);
}

if(empty($first_name) || empty($last_name)) {
die (“Sorry, you left a required field blank. Please go back and fill this out again.”);
}

$con=mysql_connect(localhost, username, password);
if (!$con) {
die(‘Could not connect: ‘ . mysql_error());
}

mysql_select_db(mydatabase, $con);

$sql=”INSERT INTO myTable (email, first_name, last_name, gender)
VALUES ($email, $first_name, $last_name, $gender)”; //do these need to be enclosed by quotes? ex ‘$email’,’$first_name’,…

[/code]

Now, I know I can do this:

$sql=”INSERT INTO myTable (email, first_name, last_name, gender)
VALUES (‘$_POST[first_name]’,’$_POST[last_name]’,’$_POST[gender]’)”;

But I figured that I had to call the variables beforehand, for the validation (is that correct)?

Also, my form names are first_name, last_name, gender and so are the table fields. Do I have to change the names in the form for this to work?

Thanks a lot for any help.

to post a comment
PHP

13 Comments(s)

Copy linkTweet thisAlerts:
@SyCoNov 06.2008 — First off this isn't necessary and even though a lot of people do it, it's not good practice to rename variables for no reason.

$email = $_POST['email'];

$first_name = $_
POST['first_name'];

$last_name = $_POST['last_name'];

$gender = $_
POST['gender'];

If they're posted vars then keep them posted vars. Unless you do something to them keep them the same then you know where they came from.

Read this page and follow the example

http://us2.php.net/manual/en/function.mysql-real-escape-string.php

You are currently vulnerable to a type of attack called SQL injection. The above function will fix that. If my first name was entered as
johnny" drop table myTable;
Then the double quote would end the first query (with an error) then the second one would execute. So if you ever accidentally gave away your table name in an error message then it'd be easy for some one to mess you up pretty good.

Always sanitize user input, however it's inputted.

Your validation might need beefing up. Currently a space would submit to the data base (trim() the input then check if it's empty) as would the email @. (at dot). Search the forums for validating an email address using preg. It's look complicated but once you get your head around it, it's not too bad.
Copy linkTweet thisAlerts:
@dtm32236authorNov 06.2008 — Wow - good stuff. Thanks a lot SyCo.

Will it help to disallow any form values with a ' or " in them? Why isn't that a common practice to avoid injections?
Copy linkTweet thisAlerts:
@SyCoNov 06.2008 — Wow - good stuff. Thanks a lot SyCo.

Will it help to disallow any form values with a ' or " in them? [/QUOTE]

You're welcome.

You need to do it for every value entered by the user. Even email contact forms need to be sanitized. Uploaded files even jpegs too. Every time you make user interaction available you open yourself up to a security risk that has to be considered.

Why isn't that a common practice to avoid injections?[/QUOTE]

Why indeed! If you assume everyone using your app is going to try to bring it down. Then you'll be ready ?
Copy linkTweet thisAlerts:
@svidgenNov 06.2008 — In many cases single/double quotes are valid characters to accept. So, simply removing them isn't a suitable solution. If a particular field should not contain quotes, it ought to be detected [and reported] by a form validation function. So, in that case, you [B]are[/B] removing them (by telling the user to).

And, it's best to assume someone will find a way to sneak some nasty sequence of characters past your validation function. So, having several layers of protection is always good.

And yes, you should be enclosing those values in quotes, like so:
[code=php]$sql="INSERT INTO myTable (email, first_name, last_name, gender)
VALUES ('$email', '$first_name', '$last_name', '$gender')"; //do these need to be enclosed by quotes? ex '$email','$first_name',... [/code]

Without quotes, MySQL will think the values in those locations are column names. So, you'll end up with a query like this:
[CODE]INSERT INTO myTable (email, first_name, last_name, gender)
VALUES ([email protected], Jon, Wire, male)";[/CODE]

MySQL will complain about syntax errors in this case, since @ is character with special meaning to MySQL. For other cases, like the first_name column, MySQL will give the following error:
[CODE]ERROR 1054 (42S22): Unknown column 'Jon' in 'field list'[/CODE]
Copy linkTweet thisAlerts:
@SyCoNov 06.2008 — In many cases single/double quotes are valid characters to accept. So, simply removing them isn't a suitable solution. [/QUOTE]

Who is saying remove them? Strip slashes when you use the data or replace the existing quotes with their ASCII equivalent before sanitizing and inserting.

From the manual.

Note: If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks.

mysql_real_escape_string

Ignore it if you want but I'd love to hear your reasons for [I]not[/I] sanitizing user input. All the cool kids are doing it now.

http://xkcd.com/327/
Copy linkTweet thisAlerts:
@dtm32236authorNov 06.2008 — Who is saying remove them?

Ignore it if you want but I'd love to hear your reasons for [I]not[/I] sanitizing user input. All the cool kids are doing it now.

http://xkcd.com/327/[/QUOTE]


hahahah, that's really funny.

I asked if I could just not allow ' or " in my form fields, but I guess that's not the best way.

I'll check out the mysql_real_escape_string and try to get that working.

Thanks a lot for the help guys.
Copy linkTweet thisAlerts:
@svidgenNov 06.2008 — Who is saying remove them?[/QUOTE]
Unless I misread it (which I didn't) dtm32236 directly asked:
Will it help to disallow any form values with a ' or " in them? Why isn't that a common practice to avoid injections? [/QUOTE]
And per the most recent post, it looks like you jumped in my face because [B]you[/B] misread it.

I accept your apology.
Copy linkTweet thisAlerts:
@SyCoNov 06.2008 — Not allowing (eg presenting a message blah isn't allowed) isn't necessarily the same as removing user content. And I'm not now nor ever was in your face mate. Etuff really isn't my thing.

I think traditionally you have to wait for an apology, accepting it in advance is a little, well you know.
Copy linkTweet thisAlerts:
@svidgenNov 06.2008 — I think traditionally you have to wait for an apology, accepting it in advance is a little, well you know. [/QUOTE]
It's a Colbert reference.
Copy linkTweet thisAlerts:
@SyCoNov 07.2008 — Ahh well Colbert's OK with me!
Copy linkTweet thisAlerts:
@MrCoderNov 07.2008 — Here is a nice little function I wrote for handling form $_POST data to MySQL.

Use..
[code=php]
if($key == "id")
continue;
[/code]

.. to skip unwanted fields within the foreach loop.


[code=php]
$fields = array();
$values = array();
foreach($_POST as $key => $value)
{
$fields[] = "".mysql_real_escape_string($key)."";
$values[] = "'".mysql_real_escape_string($value)."'";
}
$sql = "INSERT INTO mytable (".implode(",", $fields).") VALUES (".implode(",", $values).")";
mysql_query($sql) or die(mysql_error());
[/code]
Copy linkTweet thisAlerts:
@SyCoNov 07.2008 — That's a handy function. I do have a couple of comments on it that might be useful for anyone using it. As you're building the arrays with square brackets you don't need the create them before, even so I do that sometimes just for clarity. I suppose if you don't need to insert every POSTed input then you can prefix the input id with something (eg id="sql_name") then strstr() for the prefix. But yea it's a nice idea to build it in a loop.
Copy linkTweet thisAlerts:
@MrCoderNov 07.2008 — That's a handy function. I do have a couple of comments on it that might be useful for anyone using it. As you're building the arrays with square brackets you don't need the create them before, even so I do that sometimes just for clarity. I suppose if you don't need to insert every POSTed input then you can prefix the input id with something (eg id="sql_name") then strstr() for the prefix. But yea it's a nice idea to build it in a loop.[/QUOTE]

If you use the same code twice without blanking the arrays you would run in to duplicate data issues thou.
×

Success!

Help @dtm32236 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 5.20,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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