Jump to content

What is a proper way to trim data before submitting it to database?


pioneerx01

Recommended Posts

I am making a form and I am trying to figure out a proper way of trimming the user submitted data before I insert it into database. If I use such code:

 

mysql_query("INSERT INTO ``.`` (
`ID` ,
`name`
)
VALUES (
NULL , 
'$_POST[name]' 
);") 
or die(mysql_error());

 

I would do it this way but I am not sure if it is the best method:

 


$name = trim($_POST[name]);

mysql_query("INSERT INTO ``.`` (
`ID` ,
`name`
)
VALUES (
NULL , 
'$name' 
);") 
or die(mysql_error());

There's no need to give it it's own variable, but you have the right idea. The only thing you're doing is not quoting associative array keys.

 

This

$_POST['name'] = trim($_POST['name']);

mysql_query("INSERT INTO ``.`` (
`ID` ,
`name`
)
VALUES (
NULL , 
'{$_POST['name']}' 
);") 
or die(mysql_error());

 

is pretty much the same as

mysql_query("INSERT INTO ``.`` (
`ID` ,
`name`
)
VALUES (
NULL , 
'". trim($_POST['name']) ."' 
);") 
or die(mysql_error());

 

I'd pick whichever one was easier to read and follow. The less you get lost looking back at your code, the better :D

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.