信息未保存在数据库中

时间:2018-08-07 13:24:02

标签: php mysqli

我创建了一个查询,该查询应存储正在查看该网站的任何用户的IP地址,浏览器和国家/地区,但该信息未存储在数据库中。

这是完整的代码。

连接

<?php
$conn = mysqli_connect("localhost","root","","ecom_store");

获取IP的功能

function getRealUserIp(){
  switch(true){
    case(!empty($_SERVER['HTTP_X_REAL_IP'])) : 
      return $_SERVER['HTTP_X_REAL_IP'];
    case(!empty($_SERVER['HTTP_CLIENT_IP'])) : 
      return $_SERVER['HTTP_CLIENT_IP'];
    case(!empty($_SERVER['HTTP_X_FORWARD_FOR'])) : 
      return $_SERVER['HTTP_X_FORWARD_FOR'];
    default : return $_SERVER['REMOTE_ADDR'];
  }
}

获取用户浏览器的功能

function getBrowser(){
  $agent = $_SERVER['HTTP_USER_AGENT'];
  $name = 'NA';
  if (preg_match('/MSIE/i', $agent) && !preg_match('/Opera/i', $agent)) {
    $name = 'Internet Explorer';
  } elseif (preg_match('/Firefox/i', $agent)) {
    $name = 'Mozilla Firefox';
  } elseif (preg_match('/Chrome/i', $agent)) {
    $name = 'Google Chrome';
  } elseif (preg_match('/Safari/i', $agent)) {
    $name = 'Apple Safari';
  } elseif (preg_match('/Opera/i', $agent)) {
    $name = 'Opera';
  } elseif (preg_match('/Netscape/i', $agent)) {
    $name = 'Netscape';
  }
  return $name;
}

获取用户国家/地区的功能

function ip_visitor_country()
{
  $client  = @$_SERVER['HTTP_CLIENT_IP'];
  $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
  $remote  = $_SERVER['REMOTE_ADDR'];
  $country  = "Unknown";

  if(filter_var($client, FILTER_VALIDATE_IP))
  {
    $ip = $client;
  }
  elseif(filter_var($forward, FILTER_VALIDATE_IP))
  {
    $ip = $forward;
  }
  else
  {
    $ip = $remote;
  }
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "http://www.geoplugin.net/json.gp?ip=".$ip);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  $ip_data_in = curl_exec($ch); // string
  curl_close($ch);

  $ip_data = json_decode($ip_data_in,true);
  $ip_data = str_replace('&quot;', '"', $ip_data);  

  if($ip_data && $ip_data['geoplugin_countryName'] != null) {
    $country = $ip_data['geoplugin_countryName'];
  }

  return $country;
}

保存信息的功能

function save(){
  global $conn;
  $c_ip= getRealUserIp();

  $c_browser= getBrowser();

  $c_country= ip_visitor_country();

  $insert_save="insert into ip (c_ip,c_browser,c_country) 
                values('$c_ip,'$c_browser','$c_country')";

  $run_save = mysqli_query($conn,$insert_save);

  echo $insert_save;

  if($run_save){
    echo "saved";
  }else{
    echo"error";
  }
}

?>

<?php save();?>

我所有的代码都写在一页上。谢谢

1 个答案:

答案 0 :(得分:2)

您忘记在$c_ip之后添加撇号

$insert_save="insert into ip (c_ip,c_browser,c_country) 
            values('$c_ip','$c_browser','$c_country')";