首页 > 解决方案 > 如何将浏览器时间发送到 mysql 服务器以保存 php

问题描述

如何通过php将浏览器时间发送到MySQL服务器进行保存。我在互联网上搜索了很多时间,但我没有找到一个好的答案。假设我的浏览器时间是 17-Sep-2018 3:10:55

那么如何将其存储在我的数据库中。我使用 NOW(), DATE 但没有提前写 answer.thanx 。

标签: php

解决方案


您必须使用 Javascript;PHP 在服务器上执行 - 这与用户的浏览器或位置不同。

例如:

(function() {
  var url = '/some/file.php?date=' + new Date();

  fetch(url, {
    method: 'GET',
    mode: 'no-cors'
  })
  .then(response() => console.log(response))
  .catch(error => console.error('Could not complete request:', error));
})();

然后在服务器中你可以处理请求:

<?php

// request date contains the date from our JS request

if( $_REQUEST['date'] )
{
  // format it how you want it
  $date = date('j M Y h:i:s a', $_REQUEST['date']);

  // check and make sure variable exists
  if( $date )
  {
    // connect to mysql (this is not recomended... better to use some sort of library)
    $mysql = new mysqli('localhost', 'root', '', 'site');

    // safely store it with prepared statements
    $stmt = $mysql->prepare('INSERT INTO visits (visist_time) VALUES (?)');
    if($stmt = $stmt->bind_param('d', $date))
    {
      // this will execute the query
      $stmt->execute();
    }
  }
}

这不是一个完美的答案;我不确定为什么要为访问的用户获取时间戳,但理论上每次加载 JS 脚本时都可以记录时间戳。


推荐阅读