-1

How do i insert user ip address into my database using prepared statement?

I have tried this 2 codes, 1 which i got from a question asked here but i do get an empty column (i.e. the user ip address is not inserted into my database).

First code i worked with;

$ip = $_SERVER['REMOTE_ADDR']; // grab users ip address
$insert = "INSERT INTO users_signup_ip(ip_address) VALUES(?)";
$stmt = mysqli_prepare($db, $insert);
mysqli_stmt_bind_param($stmt, "s", $ip);
if (mysqli_stmt_execute($stmt)) {
   # code...
}

Second code i worked with (current);

$ip = $_SERVER['REMOTE_ADDR']; // grab users ip address
$insert = "INSERT INTO users_signup_ip(ip_address) VALUES(INET_ATON(?))";
$stmt = mysqli_prepare($db_var, $insert);
mysqli_stmt_bind_param($stmt, "s", $ip);
if (mysqli_stmt_execute($stmt)) {
   # code...
}
  • Check for errors. Does the execute return true? – Qirel Jul 25 '18 at 09:53
  • no...... @Qirel –  Jul 25 '18 at 09:58
  • You should read up on [mysqli_error()](http://php.net/manual/en/mysqli.error.php). That will help you find out _why_ the query fails. – M. Eriksson Jul 25 '18 at 10:03
  • 1
    `echo mysqli_stmt_error($stmt);` for the statement objects. Do not inject the variable directly in the query as the answer below suggested. It might work, but will not be secure. – Qirel Jul 25 '18 at 10:07

1 Answers1

0

Try the following method

$stmt = $conn->prepare("INSERT INTO users_signup_ip(ip_address) VALUES (?)");
$ip = $_SERVER['REMOTE_ADDR'];
$stmt->bind_param("s", $ip);
$stmt->execute();
Jan Myszkier
  • 2,714
  • 1
  • 16
  • 23
Faizan Fayaz
  • 540
  • 5
  • 16
  • Wrap the code in try catch block so if there is an exception you will get to know – Faizan Fayaz Jul 25 '18 at 10:02
  • 1
    As far as I know, mysqli doesn't throw any exceptions if the statement fails, which makes try/catch moot. – M. Eriksson Jul 25 '18 at 10:05
  • **Warning: mysqli_error() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\project\signup.php on line 215** @FaizanFayaz –  Jul 25 '18 at 10:20
  • `$insert = "INSERT INTO users_signup_ip(ip_address) VALUES(?)"; $stmt = mysqli_prepare($db_var, $insert);` –  Jul 25 '18 at 10:31
  • 1
    After that code write the following for checking the error. print_r(mysqli_error($db_var)); – Faizan Fayaz Jul 25 '18 at 10:39
  • i did a mistake when typing thats why, but everything now works fine @FaizanFayaz –  Jul 25 '18 at 10:43
  • Just a little thing, you don't need to copy `$_SERVER['REMOTE_ADDR']` to `$ip` to use it, just use `$_SERVER['REMOTE_ADDR']` directly with `bind_param()`, by copying you are using unnecessary memory. – Spoody Jul 25 '18 at 20:32