使用Highcharts和mysql进行页面访问

时间:2013-10-26 17:16:48

标签: php mysql sql highcharts

我正在尝试使用Highcharts来显示每个属性的用户访问次数,但是我不确定如何设置SQL查询以正确显示它。如果我们的数据库只是在特定时间段内列出了页面访问量,那将会容易得多,但每次访问时每个用户,每次访问都会存储,如下所示:

Data

我知道我必须查询每个属性的总和访问量并按月对其进行排序,但确切地说,最好的方法是超出我的要求。这就是我到目前为止所做的:

    <?php

$con = mysql_connect('localhost', 'root', 'root');
if (!$con) {
  die('Could not connect: '.mysql_error());
}

mysql_select_db('demeure', $con);

//$date_start = $_POST['date_start'];
//$date_end = $_POST['date_end'];
$date_start = '2012-07-01 00:00:00';
$date_end = '2012-08-01 00:00:00';

$result = mysql_query("
  SELECT
    COUNT(id) AS count,
    created_at
  FROM
    user_property_visits
  WHERE
    created_at BETWEEN '$date_start' AND '$date_end'");

while ($row = mysql_fetch_array($result)) {
  echo $row['count'] . "\t" . $row['created_at']. "\n";
}

mysql_close($con);

?>

这会产生一个空白页面。我不确定我能得到我需要的距离,但感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我不确定您是否需要此功能,但您可以在WHERE子句中过滤句点。检查它是否有帮助:

<?php

// Show all PHP errors.
error_reporting(E_ALL);

// Connect with MySQL
$con = mysql_connect('localhost', 'your_user', 'your_password');
if (!$con) {
  die('Could not connect: '.mysql_error());
}
mysql_select_db('demeure', $con);

// Obtain date range from $_POST or
// manually edit this.

//$date_start = $_POST['date_start'];
//$date_end = $_POST['date_end'];
$date_start = '2012-07-20 20:30:00';
$date_end = '2012-07-20 20:37:00';

// Query with GROUP BY
$result = mysql_query("
  SELECT
    COUNT(id) AS `count`,
    created_at
  FROM
    user_property_visits
  WHERE
    created_at BETWEEN '$date_start' AND '$date_end'
  GROUP BY
    created_at");

while ($row = mysql_fetch_array($result)) {
  echo 'Count: ' . $row['count'] . '<br/>' . 'Group by date: ' . $row['created_at'] . '<br/>';
}

// With the schema used in SQL Fiddle, this code will reproduce
//
// A PHP Error was encountered
// Severity: 8192
// Message: mysql_connect(): The mysql extension is deprecated and
// will be removed in the future: use mysqli or PDO instead
//
// Filename: views/home.php
//
// Line Number: 7
//
// Count: 4
// Group by date: 2012-07-20 20:36:28

mysql_close($con);

?>

使用此功能,您可以使用日期选择器来选择日期范围,并通过POST(ajax)获取此值。

Check this SQL Fiddle

答案 1 :(得分:0)

我能够用以下方法解决它:

    <?php

$host = "localhost";
$user = "root";
$pass = "root";
$database = "demeure_new";

$dsn = "mysql:dbname=$database;host=$host";
$pdo = new PDO($dsn, $user, $pass);

$query = "SELECT DAY(created_at) AS day, MONTH(created_at) AS month, YEAR(created_at) AS year, count(user_id) AS count FROM user_property_views GROUP BY day";
$stmt = $pdo->prepare($query);
$stmt->execute();

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();

$newArray = array();
foreach($result as $r)
  $newArray[$r["year"]][$r["month"]][$r["day"]] = $r["count"];

//print_r($newArray);

json_encode($result, JSON_NUMERIC_CHECK);

echo json_encode($newArray);
?>