I've created a page counter, and want to track how many times the user click the page.
So far I can track how many times they click the page, but I want to now set it so when a week is up that it will create a new entry.
My mysql_query look up is base on the user's name, seeing there is more than one user I'm tracking.
This is my code for tracking a user for a selected page:
<?php
include"lib/settings.php";
date_default_timezone_set("America/Los_Angeles");
$track_users_clicks = $_SESSION['username'];
$todays_date = date("m/d/Y H:i:s a");
$query = "SELECT * FROM page_count WHERE `username`=".sql_val($track_users_clicks);
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query."<br />Error: (".mysql_errno().") ".mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$username = $row['username'];
$counter_snippet = $row['counter_snippet'];
$date_time = $row['date_time'];
}//end while
if ($_SERVER['REMOTE_ADDR']){
$query_update = 'UPDATE page_count SET
`counter_snippet` = '.sql_val($counter_snippet + 1).',
`date_time` = '.sql_val($todays_date).'
WHERE `username` = '.sql_val($track_users_clicks);
$result = mysql_query($query_update) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query_update."<br />Error: (".mysql_errno().") ".mysql_error());
}
?>
This is so far what I've come up with for tracking a user per week:
<?php
include"lib/settings.php";
date_default_timezone_set("America/Los_Angeles");
//$track_users_clicks = $_SESSION['username'];
$todays_date = date("m/d/Y");
$begin_date = date("m/d/Y");
$end_date = date( "m/d/Y", strtotime($begin_date."+7 day" ) );
$user_log = "trevor.hanes" .$end_date;
$track_users_clicks = "trevor.hanes";
$query_begin = "SELECT * FROM date_time WHERE `username`=".sql_val($track_users_clicks);
$result = mysql_query($query_begin) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query_begin."<br />Error: (".mysql_errno().") ".mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$username = $row['username'];
$counter_snippet = $row['counter_snippet'];
$start_date = $row['start_date'];
//$end_date = $row['end_date'];
}
if ($todays_date >= $end_date){
$query_start = 'INSERT INTO date_time (
`username`,
`start_date`,
`end_date`,
`user_log`
) VALUES (
'.sql_val($track_users_clicks).',
'.sql_val($todays_date).',
'.sql_val($end_date).',
'.sql_val($user_log).'
)';
$result = mysql_query($query_start) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query_start."<br />Error: (".mysql_errno().") ".mysql_error());
}
else
{
if ($_SERVER['REMOTE_ADDR']){
if ($end_date >= $todays_date){
$query_update = 'UPDATE date_time SET
`counter_snippet` = '.sql_val($counter_snippet + 1).'
WHERE `end_date` = '.sql_val($end_date);
$result = mysql_query($query_update) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query_update."<br />Error: (".mysql_errno().") ".mysql_error());
}}}
echo $begin_date;
echo "<BR>";
echo $end_date;
echo "<BR>";
echo $user_log;
?>
So my problem is once I change the date any later than the end date, it just keeps creating new table entries. Instead of creating one new table entry for the new week then updating the hits.
Any thoughts on what I'm doing wrong.
First thing's first: You NEED to be using prepared statements. Prepared statements will prevent malicious code from profoundly impacting your database. For example, somebody could drop your entire table if you had poorly configured user privileges by getting the following text into $_SESSION['username']:
; DROP TABLE page_count;
This looks like a decent tutorial on PDO (most common way to use prepared statements in PHP) at: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Anyway, to actually answer your question, use a query like the following:
SELECT *, YEARWEEK(date_time) as week,
FROM page_count WHERE `username` = :USERNAME
GROUP BY week;
Documentation for YEARWEEK: http://www.techonthenet.com/mysql/functions/yearweek.php
Related
I am taking a users input and storing it in a database, however I want to be able to update the records if a user adds more information. So I want to search the database find the server with the same name and update the the last downtime and the number of downtimes.
$connect = mysqli_connect("localhost", "Username", "Password","Test_downtime");
if (!$connect)
{
die("Connection failed: " . mysqli_connect_error());
}else
{
echo "Connected successfully\n";
}
$servername = $_GET["server_name"];
$downtime = $_GET["downtime"];
$time_now = time();
$result = mysqli_query($connect, "SELECT COUNT(*) FROM `Test_downtime`.`Downtime` WHERE `Server_Name` = '$servername'");
$row = mysqli_fetch_array($result);
// If no downtime have been reported before
if ($row[0] == 0){
$sql = mysqli_query($connect, "INSERT INTO `Test_downtime`.`Downtime` (ID, Server_name, First_downtime, Last_downtime, Num_of_downtime,Total_downtime) VALUES (NULL, '$servername', '$time_now','$time_now',1,'$downtime'); ");
if ($sql==true) {
echo $servername . " has has its first downtime recorded\n";
}
}
//If users is already in the database
else{
$numdowntime = ($row["Num_of_downtime"] + 1);
$id = ($row["ID"]);
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
if ($sqlupdate == TRUE) {
echo "Oh No! " . $servername . " has had ". $numdowntime ." of downtimes" ;
}
}
?>
The program works fine if the server is not already in the database, the problems arise if the server is already in the database. I get the message saying it has been updated yet nothing happens to the database. How do i make it so it search and updates the records for the searched item.
So nothing append since you do not execute the sql statement ^^
Take a look here :
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
You need to use :
$sql = mysqli_query($connect, $sqlupdate);
Just after it in order to execute it.
Or at least change it to
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
Btw there is other problem but here is the main one [check out the other answer in order to found another one ]
you are fetching the result as indexed array
mysqli_fetch_array($result);
and here you are accessing results as associative array
$numdowntime = ($row["Num_of_downtime"] + 1);
change your query to
mysqli_fetch_assoc($result);
use
mysqli_num_rows($result);
to checking if you have any data
change
if ($row[0] == 0){}
to
if(mysqli_num_rows($result) ==0){}
A good approach for increasing a count in a column is using SQL to increase that.
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = (`Num_of_downtime` + 1), `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
This way you can skip your $numdowntime calculation, and the result is more accurate.
In your current setup, two users may fire the event at the same time, they both retrieve the same number from the database (ie. 9), both increasing it with one (ie. 10), and writing the same number in the database.
Making your count one short of the actual count.
SQL takes care of this for you by locking rows, and you are left with a more accurate result using less logic :)
You miss the mysqli_query() function, which actually queries the database.
$sqlupdate = mysqli_query("
UPDATE `Test_downtime`.`Downtime`
SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now()
WHERE `Server_Name` = '$servername'"
);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to create 24hr period from database creation date with this code but I have mysql_fetch_assoc problem when I want to echo dif its show wrong format I need just secounds!
//connect to database
//....
//get time difference in seconds from last execution
$sql1 = "SELECT TIME_TO_SEC(TIMEDIFF(NOW(), last_ts)) AS tdif FROM php_cron";
$res1 = mysql_query($sql1) or die("[1] MySQL ERROR: ".mysql_error());
while ($dif = mysql_fetch_assoc($res1)) {
echo $dif["tdif"] ;
}
if ($dif >= 86400) { //24h
//following code will run once every 24h
//update user's page rank
$sql2 = "UPDATE myTable SET `user-rank` = `user-rank` + 10";
mysql_query($sql2) or die("[2] MySQL ERROR: ".mysql_error());
//update last execution time
$sql3 = "UPDATE php_cron SET last_ts = NOW() WHERE id=1";
mysql_query($sql3) or die("[3] MySQL ERROR: ".mysql_error());
}
It will be better if you can access to all dates of column :) can anyone help?
========================================================================================////////////
I put counter for ID. is there any other better way? thanks
$idcount = 1;
while ($dif = mysql_fetch_assoc($res1)) {
echo $dif["tdif"];
echo "<br>";
if ($dif["tdif"] >= 86400) { //24h
//update user's page rank
$sql2 = "UPDATE deposit SET `earn` = `earn` + 10 where id=" . $idcount . "";
mysql_query($sql2) or die("[2] MySQL ERROR: ".mysql_error());
My guess is this is actually what you want to do. Notice I moved the if statement inside of the while loop and changed $dif to $dif["tdif"].
$sql1 = "SELECT TIME_TO_SEC(TIMEDIFF(NOW(), last_ts)) AS tdif FROM php_cron";
$res1 = mysql_query($sql1) or die("[1] MySQL ERROR: ".mysql_error());
while ($dif = mysql_fetch_assoc($res1)) {
echo $dif["tdif"];
if ($dif["tdif"] >= 86400) { //24h
//update user's page rank
$sql2 = "UPDATE myTable SET `user-rank` = `user-rank` + 10";
mysql_query($sql2) or die("[2] MySQL ERROR: ".mysql_error());
//update last execution time
$sql3 = "UPDATE php_cron SET last_ts = NOW() WHERE id=1";
mysql_query($sql3) or die("[3] MySQL ERROR: ".mysql_error());
}
}
I have a database field which are
Appt_Datetime (which is call as DateTime in my table)
Svc_ID (which i call ApptType in my table)
I wanted the system to let the customer know that the datetime for the appt type is not available once someone else has book that slot.I have done a lot of research and trying out different codes but to no avail. I've seen answers on stackoverflow that uses PDO but im not so clear about it hence i'd like something to do with mysql. I have been stuck at with this at least few weeks now. Help
This is my call func:
$datetime = $_POST['DateTime'];
$appt = $_POST['ApptType'];
This is the query i last tried out but still is not working:
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
if($row==1)
{
echo "Date in not available";
}
else if($row==0)
{
$query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn);
}
Hint:
change this to $result = mysql_query($query, $conn); to $result = mysql_query($vquery, $conn);
at the time you are using $conn you do not have $query it is $vquery:
$result = mysql_query($vquery, $conn);
And as suggested above in comments better use mysqli or PDO.
you can try this condition..
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
if($result = mysql_query($vquery, $conn)){
//$row = mysql_fetch_assoc($result);
if(mysql_num_row($result)>0)
{
echo "Date in not available";
}
else
{
/* $query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn); */
echo "insert";
}
}else{
echo mysql_error();
}
I'm creating a web page which has events with different dates which are printed out from my database using php. I want it so the events which have gone past the current date automatically do not show on the page.
I'm using the 'date' type in mySQLi for holding the date and when i'm inserting the date into my database i'm using the code;
<?php
if($db_server){
$eventdate = clean_string($db_server, $_POST['eventdate']);
$timeDate = strtotime($eventdate);
$tempdate = date("Y-m-d", $timeDate);
$query = "INSERT INTO events (eventdate) VALUES ('$tempdate')";
mysqli_query($db_server, $query) or
die("Insert failed. ". mysqli_error($db_server));
$message = "Event Uploaded";
}else{
$message = "Error: could not connect to the database.";
}
?>
Event Date: <input type="event-upload" class="standard" name="eventdate" id="datepicker" />
Here's the code when i'm printing out the date;
<?php
if($db_server){
$query = "SELECT * FROM events";
$result = mysqli_query($db_server, $query) or die(mysqli_error($db_server));
if (!$result) die('Query failed: ' . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
echo $row['eventdate']
}
}
?>
If someone could help me out it and tell me what the right WHERE clause is to use, it would be much appreciated.
$query = "SELECT * FROM events WHERE eventdate >= '".date("Y-m-d")."'";
Is that what you're looking for?
Use this using DATEDIFF function in mysql
select * from `events` where DATEDIFF(`eventdate`,now() ) > 0
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);
?>