How do I add an ip address to MySQL INSERT INTO database code?

How do I add the $ip address form field to this database code?

$form_vars = array('one','two','three');

$ip = getenv("REMOTE_ADDR");    

$query = "INSERT INTO recommended SET ";
for ($i = 0; $i < count($form_vars); $i++) {
 $query .= $form_vars[$i].'="'.AddSlashes($_REQUEST[$form_vars[$i]]).'",';              
}

$query .= 'DateTime="'.date('y/m/d g:i a').'"';
$result = mysql_query($query) or die("Error in query: $sql. ".mysql_error());

The get $IP line is there but I can’t get it to work in the Insert.

I’ve just reused this code over time but it seems there are 3 assignments to $query. Is there a simpler way to write this since it’s used all the time?

Thanks!

Answer

You never add it in the array :

$form_vars = array('one','two','three');
$ip = getenv("REMOTE_ADDR");    

$query = "INSERT INTO recommended SET ";
for ($i = 0; $i < count($form_vars); $i++) {
 $query .= $form_vars[$i]."='".mysql_real_escape_string($_REQUEST[$form_vars[$i]])."',";              
}
$query .= "my_ip_column = '". $ip . "',";
$query .= "DateTime='".date('y/m/d g:i a')."'";

Notice I switched double quotes and single quotes : in SQL, strings are surrounded by simple quotes.

Instead of escaping all users input, you can use prepared statements. Have a look at this document. You can also read all the documentation about mysqli. mysql_ functions are now deprecated.

Leave a Reply

Your email address will not be published. Required fields are marked *