Jump to content

function question.


fife

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

if(isset($_POST['submit_member'])){   

//trim
$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";    
}    

//mysql_real_escape_string!
$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) 
        { 
           $$key=trim(mysql_real_escape_string(($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

 

eg

 

$_POST['name'];

$_POST['description'];

 

Would they come out like....

 

$name

$description

 

??????

 

Link to comment
https://forums.phpfreaks.com/topic/228287-function-question/
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
https://forums.phpfreaks.com/topic/228287-function-question/#findComment-1177201
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
https://forums.phpfreaks.com/topic/228287-function-question/#findComment-1177205
Share on other sites

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.