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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How do I add an ip address to MySQL INSERT INTO database code? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about How do I add an ip address to MySQL INSERT INTO database code? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji