Jump to content

function question.


Recommended Posts

Hi  I have a question about a function someone gae to me.  When Im inserting data into the database from a form I always follow the same format. for example let say I have name, description number...


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

//check for errors
$errors = array();    
if(empty($name))    {        
$errors[] = "Please enter a name";    
if(empty($description))    { 
$errors[] = "Please enter a description";    

$name    = mysql_real_escape_string($name);        
$description      = mysql_real_escape_string($description );        
$number           = mysql_real_escape_string($number);    

then the insert into the database here ......



now if you have a lot of fields you will be repeating yourself constantly.  On this basis my friend gave me this code...

foreach ($_POST as $key => $value) 


The first question is... is my friend right and should it be written this way.  The second question is what would the the data come out like







Would they come out like....







Link to comment
Share on other sites

Ok well I have re-written it now to look like this..

function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = mysql_real_escape_string($data);
return $data;



Now when returning data from the form I run it through the function before it goes into the database.  Is this best practise.  The code seems so small leaner but some of the functions no matter how many times I read about them they just seem to make no sense.

Link to comment
Share on other sites

You shouldn't be arbitrarily applying stripslashes() to data, you need to check if( get_magic_quotes_gpc() ), and only then apply stripslashes(). There's no reason to use htmlspecialchars() to insert data into a database, that would be used when displaying the data.

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • 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.