Using Highcharts with mysql for Page Visits - php

I am trying to use Highcharts to display user visits per property, however I am unsure how to set up the SQL query to properly display this. It would be a lot easier if our database simply listed page visits during specific periods of time, but it's stored per-user, per-property, per visit, as you can see here:
I know that I have to query the sum visits per property and sort it by month, but exactly the best way to do this is beyond me. This what I've got so far:
<?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);
?>
This results with a blank page. I'm not sure how close I am to getting what I need, but thanks for the help.

I'm not sure if you want this, but you can filter the period in the WHERE clause. Check if it could help:
<?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);
?>
Using this, you can use a datepicker, for example, to select the date range and obtain this values via POST (ajax).
Check this SQL Fiddle

I was able to solve it with the following:
<?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);
?>

Related

The total number of mysql results not displaying properly

I am working on a total page view system and each time someone visits a page it adds the current data and their ip address. When I go to display the total number of rows on a particular day the site just displays 'Rows' without the number.
Code:
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
$date = date("Y-m-d-h-m-s");
$ip = $_SERVER['REMOTE_ADDR'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$date = date("Y-m-d");
$result = mysqli_query("SELECT FROM page_views WHERE date = $date");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
$conn->close();
?>
Could someone please indicate what is going wrong.
Your query is failing but you don't know it because you don't check for errors. If you did you would see a syntax error due to you omitting the * from your SELECT clause and your date not being in quotes.
Change:
$result = mysqli_query("SELECT * FROM page_views WHERE date = $date");
to:
$result = mysqli_query("SELECT * FROM page_views WHERE date = '$date'");

Choose results by date filter PHP and MySQL

I have one page (members.php) that post date to another page (results.php). Using the below code, i can successfully get the "to" and "from" variables from the members page.
<?php echo $_POST["to"]; ?>
<?php echo $_POST["from"]; ?>
My problem now is, how can i create a query (in results.php) in order to show filter results only for the dates that are specified at the above variables? Do i need to create an sql connection and sql query too?
If dates are in YYYY-mm-dd format then you can use it as below otherwise you need to change the format.
You can do as below :
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//$from_date = $_POST['from_date'];
//$to_date = $_POST['to_date'];
$from_date = date("Y-m-d",strtotime('06/10/2015'));
$to_date = date("Y-m-d",strtotime('06/16/2015'));//$_POST['to_date'];
$query = "SELECT * FROM table WHERE from_date >= '".$from_date."' AND to_date <= '".$to_date."'";
// Perform Query
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
You should connect to database and compare this two dates:
$dateOne = $_POST["from"];
$dateTwo = $_POST["to"];
If bigger date is 0, then you should always make it the highest date possible to successfully query Data:
if(empty($dateTwo))
{
$dateTwo = date("31-12-Y");
//If $dateTwo is null, than it will be 31/12/2015 otherwise query will now work well
}
Then you should write sql query like this:
"SELECT * FROM `table` where `dateOne` > '$dateOne' and `dateTwo` < '$dateTwo'";
In this case if user wants all dates bigger than dateOne but doesn't check dateTwo, this query will return all data bigger than dateOne and lower than highest date available in current year (In our case it's 31/21/2015).
Its not necessarily creating a new sql connection but just a new query (proposed you have already connected to the database). In my opinion, if you want to display the results between the two dates.
I am not checking for existing or empty values since the dates have been already given.
So:
<?php $start_date = $_POST["from"];
$end_date = $_POST["to"];
//sql will be
$sql = "SELECT * FROM `your_table` WHERE `the_date_column` BETWEEN {$start_date} AND {$end_date}";
?>
Please but doing this use mysqli or PDO connection layer and also try to escape the variables to prevent sql injection or better off, use prepared statements.
SELECT * FROM sales WHERE build_date BETWEEN '$start_date' AND '$end_date';

Display amount of registered users in MySQL database using PHP

I want to display the current amount of users registered in my database (it's called dalton) / the users are stored in a table in that database called simpleauth_players. It stores their name, hash, registerdate, logindate, and lastip.
I want to somehow use a PHP code that (logs me into the database) and displays the current amount of names in the database. So I can display a message like "Hey, there is currently 1,894 registered players!" inside of my HTML/PHP page. I'm kinda a novice it would be awesome if somebody could share the code and instructions.
My code:
$connection = mysql_connect('host', 'username', 'password');
mysql_select_db('database');
$query = "SELECT * FROM simpleauth_players";
$result = mysql_query($query);
$registered = "SELECT COUNT(*) FROM dalton.tables WHERE simpleauth_players = 'name' and TABLE_TYPE='BASE TABLE';
echo "$registered";
mysql_close();
This is the code I used to display the amount of registered players (AKA rows) in the simpleauth_players table.
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("dalton", $link);
if ($_GET['task'] == 'total') {
$get_db = 'simpleauth_players';
$result = mysql_query("SELECT * FROM $get_db", $link);
echo '{"task":"total","amount":"';
echo mysql_num_rows($result);
echo '"}';
}
?>
select count(*) as total_player from simpleauth_players
OR
$sql = "select * from simpleauth_players";
$result = mysqli_query($con,$sql);
$count = mysqli_num_rows();
echo "Total ".$count." Players";
Try this one assumed that your column name is language
SELECT COUNT(*) FROM simpleauth_players WHERE language = "PHP"
or if you want to get count by each language type you can use this
SELECT COUNT(DISTINCT user_id) AS Count,language FROM simpleauth_players GROUP BY language
As per your original post/question Since you have not provided us with the MySQL API you're using to connect with, here's an mysqli_ version, using MySQL's aggregate COUNT() function, which will count the number of given rows in a table:
$connection = mysqli_connect('host', 'username', 'password', 'database');
$result = mysqli_query($connection, "SELECT COUNT(*) as count
FROM simpleauth_players"
);
while ($row = mysqli_fetch_array($result)) {
$var = $row['count'];
echo "There are currently " .$var. " users.";
}
Edit: if using mysql_
$connection = mysql_connect('host', 'username', 'password');
if (!$connection) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('database', $connection);
if (!$db_selected) {
die ('Can\'t use database : ' . mysql_error());
}
$result = mysql_query("SELECT COUNT(*) as count
FROM simpleauth_players", $connection);
while ($row = mysql_fetch_array($result)) {
$var = $row['count'];
echo "There are currently " .$var. " users.";
}

mySQL statement not running in PHP variable declaration

In the following code I'm attempting to connect to my database, pull the maximum ID from my table and then generate a random number using the the rand() function. The code successfully connects me to the the database but when I try to call for the maximum ID it won't return a value.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) FROM 'table'";
$rannmr = rand(1, $amount);
// Close the mysql connection
mysqli_close($dbLink);
?>
Any help in resolving this would be appreciated.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
Firstly, you are using the wrong identifier for FROM 'table' being single quotes.
If table is indeed the table's name, wrap it in backticks, your question shows file.
$amount = "SELECT MAX(id) FROM `table`";
Either way, you cannot use quotes around a table name. It appears you are using file as your table name.
So if table is only an example and it is called file let's just say, you would do:
$amount = "SELECT MAX(id) FROM `file`";
or
$amount = "SELECT MAX(id) FROM file";
Then, you also need to query, using mysqli_query() which you are not doing.
$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`");
Or Object oriented style:
$amount = $dbLink->query("SELECT MAX(id) FROM `file`");
if($amount){
echo "Success!";
}else{
die('Error : ('. $dbLink->errno .') '. $dbLink->error);
}
See example #1 from http://php.net/manual/en/mysqli.query.php
Use or die(mysqli_error($dbLink)) to mysqli_query() which would have signaled the error.
http://php.net/manual/en/mysqli.error.php
Edit:
Try the following. You may need to modify $row[0] and rand(0,$count) as 1 depending on the column number.
$result = $dbLink->query("SELECT MAX(id) FROM mytable")
while ($row=$result->fetch_row()) { $count = $row[0]; }
$random = rand(0,$count);
echo $random;
use this:
$amount = "SELECT MAX(id) FROM table";
You forgot to execute the MySQL-query:
$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc();
$rannmr = rand(1, $amount[0]);
You never executed the query, you need more logic
if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
if ($row = mysqli_fetch_assoc($result)) {
$amount = $row['amount'];
$rannmr = rand(1, $amount);
}else{
echo 'no row found';
}
}
mysqli_close($dbLink);
I didn't seem to see the line of code which actually does the query:
Try this: Using the object-oriented mysqli approach
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) as max_id FROM 'table'";
// Do the actual query :
$run_query = $dbLink->mysql->query($amount);
// Retrieve the values:
$result = $run_query->fetch_array();
// Do the rand function together with the retrieved value
$rannmr = rand(1, $result['max_id']);
// Now you can echo the variable:
echo $rannmr;
// Close the mysql connection
mysqli_close($dbLink);
?>
Thanks!!

php/mysql: get data from one table, convert and insert in another table

Ok I will try to explain, (I am Portuguese lol).
I have a Database where I have the fallowing MySQL:
Database: ad
Table: notebooks
Fields: ID, tag, so, lastlogon, lastlogh
My ldap query gets data from ldap server (active directory) and stores it in my MySQL database (ad/notebooks).
I get tag which is tag number is unique.
I get so which is the OS installed in the notebook.
I get lastlogh which is the last logon time stamp, and it is unique too.
ID field is auto increment and key but I can set the tag filed to be key.
I have a config_notebooks.php where I set all the variables to connect to ldap and MySQL servers.
<?php
/*------------------------------------------------------------------------*/
//setting your variables
/*------------------------------------------------------------------------*/
//ldap host
$host = "ldap://HEICPT1VIA01.HEIWAY.NET";
//ldap user
$user = "domain\user";
//ldap password
$pswd = "pssw";
//ldap base structure
$dn = "OU=NotebookM2,OU=WorkstationsM2,OU=PT1,DC=heiway,DC=net";;
//attributs to search and get
$attrs = array("cn","operatingsystem","lastlogon");
//sql host
$sqlhost="localhost";
//sql user
$sqluser="root";
//sql password
$sqlpswd="";
//sql database
$database="ad";
//sql table
$table="notebooks";
?>
Now the query script
<?php
/*------------------------------------------------------------------------*/
//Query script
/*------------------------------------------------------------------------*/
include 'config_notebooks.php';
$filter = $_POST['filter']."=".$_POST['keyword']."*";
//connect to db
$con = mysql_connect("$sqlhost","$sqluser","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//connect to active directory
$ad = ldap_connect($host)
or die( "Could not connect!" );
// Set version number
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3)
or die ("Could not set ldap protocol");
// Binding to ldap server
$bd = ldap_bind($ad, $user, $pswd)
or die ("Could not bind");
$search = ldap_search($ad, $dn, $filter, $attrs)
or die ("ldap search failed");
$entries = ldap_get_entries($ad, $search);
$sel = mysql_select_db("ad", $con);
if (!$sel)
{
die('Could not select DB: ' . mysql_error());
}
for ($i=0; $i<$entries["count"]; $i++)
{
$tag = $entries[$i]["cn"][0];
$so = $entries[$i]["operatingsystem"][0];
$lastl = $entries[$i]["lastlogon"][0];
mysql_query("
INSERT INTO
$table (tag, so, lastlogh)
VALUES
('$tag', '$so', '$lastl')
ON DUPLICATE KEY UPDATE
tag='$tag',
so='$so',
lastlogon='$lastl'
");
}
mysql_close($con);
ldap_unbind($ad);
if ($entries["count"] > 0)
header("Location: notebooks_list.php")
?>
In this query the last logon timestamp is coded like 130276262860634000
So I can export everything to excel and decode it, but I found a code that does that, so it saves time.
I created a new field in the database (lastlogon) and I need to fetch the data from lastlogh field, decode with the new script and store it in the lastlogon field.
This is the script that I found:
<?php
function adConvert ($ad) {
$seconds_ad = $ad / (10000000);
//86400 -- seconds in 1 day
$unix = ((1970-1601) * 365 - 3 + round((1970-1601)/4) ) * 86400;
$timestamp = $seconds_ad - $unix;
$normalDate = date("F d, Y", $timestamp);
return $normalDate;
}
//example: echo adConvert($ad);
?>
Using Mysql API
$res = mysql_query("SELECT * FROM $table");
while($row = mysql_fetch_assoc($res)) {
$logon_ts = adConvert($row['lastlogh']);
mysql_query("UPDATE $table SET lastlogon = '$logon_ts' WHERE tag='$row[tag]'");
}
I hope this solves your problem.
Note: Mysql API is deprecated as of PHP 5.5.0. So, It's highly recommended to use Mysqli API for newer developments.
man.. use the distinct for resolve u problem http://www.w3schools.com/sql/sql_distinct.asp

Categories