PHP View Counter - php

I am trying to make a website and it's almost completed but I want to add a view counter so when someone visit the page it count the view and save it into the database.
My script is working fine but the problem is that it continue view count even visitor is viewing anyother page
My pages url show like this
pictures.php?ID=13
I have added this PHP code in *count.php*
<?php
session_start();
if (isset($_SESSION['views'])){
$_SESSION['views']++;
} else {
$_SESSION['views'] =0;
}
//echo $_SESSION['views'];
?>
Page *views.php*
<?php
session_start();
if (isset($_SESSION['$post_id'])){
$_SESSION['$post_id']++;
} else {
$_SESSION['$post_id'] =0;
}
//echo $_SESSION['views'];
?>
<?php
echo "<hr><div align=\"center\">";
echo $_SESSION['$post_id'];
?>
<?php
$save = $_SESSION['$post_id'];
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE save_data SET Views='$save' WHERE ID='$page_id'");
mysqli_close($con);
?>
And added this line in Pictures.php where I want to show and count visits
<?php include("views.php"); ?>
Problem:
When someone visits page pictures.php?ID=8 it will show him page view 1 and save this view in database where ID=8, when he visit page pictures.php?ID=12 it will show him view 2 and save this 2 in database where ID=12. My point is that it is continuously counting instead of each page view.
Thanks in advance
Here is Pictures.php
<?php
include("connection.php");
if(isset($_GET['ID'])){
$page_id = $_GET['ID'];
$select_query = "select * from save_data where ID='$page_id'";
$run_query = mysql_query($select_query);
while($row=mysql_fetch_array($run_query)){
$post_id = $row['ID'];
$post_title = $row['Title'];
$post_image = $row['Name'];
?>
<h3>
<a href="pictures.php?ID=<?php echo $post_id; ?>">
<?php echo $post_title; ?>
</a>
</h3><center>
<form id="search-form" action="javascript:void(0);">
<input type="text" id="dimen" name="dimension" />
<input type="submit" value="Resize" Onclick ="splitString()"/></form>
<div id="sizet">
Type size like 200*300 in box
</div></center>
<div id="img"><img id="myImage" src="uploads/<?php echo $post_image; ?>" /></div>
<?php } }?>
<center>
<div id="postdetails">
<?php include("posted_by.php"); ?></center>
</div>
<?php include("views.php"); ?>
<html>
<link href="css/Pictures.css" rel="stylesheet" type="text/css">
<body>
<head>
<script type="text/javascript">
function splitString()
{
var myDimen=document.getElementById("dimen").value;
var splitDimen = myDimen.split("*");
document.getElementById("myImage").width=splitDimen[0];
document.getElementById("myImage").height=splitDimen[1];
}
</script>
</head>
</body>

Variables inside of single quotes are not evaluated, so regardless of whether $post_id is 8 or 12, $_SESSION['$post_id'] is setting the key named literally $post_id, rather than the key named 12 or 8. Variables are evaluated inside double quotes, so $_SESSION["$post_id"] would work, but the simplest and best way is to use $_SESSION[$post_id] instead.
Additionally, using $_SESSION here is probably not what you want to do. $_SESSION will be different for every user who visits the site, so when a new visitor comes to the site, it will start over with a count of 1. What you probably want to do is load the views value from the database, add one to it, and then save it back to the database. $_SESSION is for keeping data that is specific to a certain user.

Try to use structure like this
$_SESSION['view'][{resource_name}_{resource_id}]
E.g. for picture with id 8 it will be
$_SESSION['views']['picutures_8']++

Related

How to display different ccs-style depending on php condition

Basically, I have an upvote or downvote button for users. When users click the upvote or downvote, the corresponding button changes depending on the user input.
My problem is how do I display which post did the user upvoted or downvoted when a user refreshes the page?
Here's my code:
<?php
if(user_upvoted){
?>
<style>
.button<?php echo $button_id;?>
{//css for upvote}
</style>
<?php
}
else if(user_downvote){
?>
<style>
.button<?php echo $button_id;?>{//ccs for downvote}
</style>
<?php
}
?>
Here is my buttons' code:
while($row=$query -> fetch(PDO::FETCH_ASSOC))
$nid = $row['nid'];
{
<button class="button<?php echo $nid;?>" id="<?php echo $nid ; ?>" name="up">
}
This works but this code seems so dirty and don't feel right if you get my meaning.
PS: This is also in a php while loop that's why this is the method I tried.
What's a cleaner method of doing this
You can code as below:
<?php
while($row=$query -> fetch(PDO::FETCH_ASSOC))
{
$nid = $row['nid'];
// Write your logic here for $user_upvoted and $user_downvote variable
$btnExtraClass = '';
if($user_upvoted){
$btnExtraClass = 'button_upvote';
}
if($user_downvote){
$btnExtraClass = 'button_downvote';
}
?>
<button class="button<?php echo $nid;?> <?php echo $btnExtraClass;?>" id="<?php echo $nid ; ?>" name="up">
<?php
}
?>
and then write your CSS rules separately.
<style>
.button_upvote {......}
.button_downvote {......}
</style>
your question seems bit confusing. Can you first help me explain below points
1) Are you storing your upvote/downvote selected by user in the database ?
Also why are you suing class here
if(user_upvoted){
?>
<style>
.button<?php echo $button_id;?>
{//css for upvote}
</style>
It should be an id. if you are uniquely identifying them, then go for a id

A log out issue (PHP)

I am not an expert in PHP, and all that I know comes from tuts. I try anyway to do the best I can by myself, but now I have a problem and cannot find what is causing the issue.
I made a bolg using this tutorial. The tutorial is great, easy to understand and everything, the only BUT is that they don't explain how to make a control panel/admin system. So, I made one by myself! I created a simple php/html5 file with icones for the functionalities that exist in the blog: "Add a new blog entry", "Edit an existing blog entry", "Add/manage categories" and "Log out". For the log in mechanism I used this other tutorial. Everything is working fine except for one thing:
After one has logged in the control panel and presses in one of the functions (let's say "Add a new blog entry") and then presses on the button "Back to the control panel", the system automatically logs out and forces you to log in again.
Anybody can explain me why? Bellow is the code of my control panel and the check.php which is included on the control panel (I cut off unnecessary code for other functions like slide shows, css sheets and others):
Control Panel:
<?php require('autent/check.php'); ?>
<p style="background:#48c248; line-height:30px; vertical-align:middle; color:#fff; font-weight:bold;">If you can see this, you're logged in</p>
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- Rich text editor -->
<script src="ckeditor/ckeditor.js"></script>
</head>
<body>
<div class="row">
<div class="twelve columns">
<h4>Useful links</h4>
<h5>Archive</h5>
<p>
<?php
mysql_connect ('localhost', 'dbuser', 'dbpass') ;
mysql_select_db ('tablename');
$result = mysql_query("SELECT FROM_UNIXTIME(timestamp, '%Y') AS get_year, COUNT(*) AS entries FROM php_blog GROUP BY get_year");
while ($row = mysql_fetch_array($result)) {
$get_year = $row['get_year'];
$entries = $row['entries'];
echo "Entries from " . $get_year . " (" . $entries . ")<br />";
}
?>
</p>
<h5>Category Archive</h5>
<p>
<?php
mysql_connect ('localhost', 'dbuser', 'dbpass') ;
mysql_select_db ('tablename');
$result1 = mysql_query("SELECT * FROM php_blog_categories ORDER BY category_name ASC");
while($row = mysql_fetch_array($result1)) {
$result2 = mysql_query("SELECT COUNT(`id`) AS entries FROM php_blog WHERE category = $row[category_id]");
$num_entries = mysql_fetch_array($result2);
echo '' . $row['category_name'] . ' (' . $num_entries['entries'] . ')<br />';
}
?>
</p>
</div>
<h4>Control panel - Manage your blog</h4>
<img src="../images/new_blog.png" title="Add a new blog entry" alt="Add a new blog entry"/><br>
<p>Add a new blog entry</p>
</div>
<div class="four columns">
<img src="../images/edit_blog.png" title="Edit a blog entry" alt="Edit a blog entry"/><br>
<p>Edit an existing blog entry</p>
</div>
<div class="four columns">
<img src="../images/cat_blog.png" title="Add/manage categories" alt="Add/manage categories"/><br>
<p>Add/manage categories</p>
</div>
<div class="four columns">
<p> </p>
</div>
</div>
<div class="four columns">
<img src="../images/logout.png" title="End your session" alt="End your session"/><br>
<p>End your session</p>
</div>
<!-- other html and footer follows -->
</body>
</html>
check.php
<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
header("Location: login.php");
exit;
} else {
// the session variable exists, let's check it's valid:
require('autent/config.php');
$userexists = false;
foreach($users as $username => $password) {
if (md5($username.$password.$salt) == $_SESSION['loggedin'])
$userexists = true;
}
if ($userexists !== true) {
exit('<p style="background:#fd0000; line-height:30px; vertical-align:middle; color:#fff; font-weight:bold;">Invalid session: please login.</p>');
}
}
?>
It may because of session timeout problem.try to increase the session time by referring the following url.
How do I expire a PHP session after 30 minutes?
Session variables are stored on your server, not on the users computer like a cookie. So the user can't ever modify $_SESSION variables. It is helpful to create a boolean variable in your session that can be used as a quick flag to tell you if the user is still signed in.
When you create the session for the user, you could create a session variable like this:
$_SESSION['valid'] = TRUE;
From here on out, all you have to do is check if the session is still set to true:
session_start();
if (!$_SESSION['valid']) {
header("Location: login.php");
exit;
}
That code checks if the session is not true and if it is not, send them to login.php
When you sign them out, you can unset the session variable or just set it to false.

displaying accurate results

I'm creating a web site directory for my mobile site (FOUND HERE)
I have figured out how to display listings from my mysql table to my home page from my tables promo_cat list.
The thing im having trouble with is this:
once clicking on one of the catagories it leads me to my list.php page.
How do I get this page to display results related to the category clicked and not others?
For example:when clicking on "FREE" brings up this page: http://www.xclo.mobi/xclo2/list.php?id=FREE. Which displays all results. it should only display results that have a promo_cat field as "FREE" and should not display any other results as it does currently.
My list.php code:
<?php
include_once('include/connection.php');
include_once('include/article.php');
$article = new article;
$articles = $article->fetch_all();
?>
<html>
<head>
<title>xclo mobi</title>
<link rel="stylesheet" href="other.css" />
</head>
<body>
<?php include_once('header.html'); ?>
<div class="container">
Category = ???
<ol>
<?php foreach ($articles as $article) { ?>
<div class="border">
<a href="single.php?id=<?php echo $article['promo_title']; ?>" style="text-decoration: none">
<img src="<?php echo $article['promo_image']; ?>" border="0" class="img" align="left"><br />
<img alt="" title="" src="GO.png" height="50" width="50" align="right" />
<font class="title"><em><center><?php echo $article['promo_title']; ?></center></em></font>
<br /><br />
<font class="content"><em><center><?php echo $article['promo_content']; ?></center></em></font>
</div><br/><br />
</a>
<?php } ?>
</ol>
</div>
</body>
</html>
/include/article.php
<?php
class article {
public function fetch_all(){
global $pdo;
$query = $pdo->prepare("SELECT * FROM mobi");
$query->execute();
return $query->fetchAll();
}
public function fetch_data($promo_title) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM mobi WHERE promo_title = ?");
$query->bindValue(1, $promo_title);
$query->execute();
return $query->fetch();
}
}
?>
You need to make changes to the code for list.php based on the input it gets through GET parameter. something like:
if ($_GET['id'] == 'FREE'){
// do something like display FREE items
}
elseif($_GET['id'] == 'GIFT') {
// display GIFT items
}
else {
// perform some default action
}
This is to make it even more database driven (helpful when there are many categories):
$sql = "select * from categories where id = '".$_GET['id']."'";
if (mysql_results($sql)){
// do something
}
else {
// show error
}
Note that this is for demo only and in your code you should use PDO/MySQLI and prepared statements and not mysql_results function.
In light of more information provided by OP:
Change this
$articles = $article->fetch_all();
to
$articles = $article->fetch_data($_GET['id']);
in list.php and see if you get correct results.
Based on the code you provided, try this:
<?php foreach ($articles as $article) {
if ($article['promo_cat'] === 'FREE') { ?>
// Keep the rest of the code
//instead of <?php } ?> - put...
<?php } } ?>
Keep in mind, this is messy. But the foreach statement (I imagine) is being used to print out all posts. So, before printing out a post, you just check to see if the promo_title is FREE, GIFT, etc. If it's not, then it doesn't print that item.
You can make this more dynamic by passing in a $_GET variable (which you apparently are doing, but the code is never using this variable) with the current promo title and altering the conditional line to say
if ($article['promo_cat'] === $_GET['id'])
Hope that helps!

echo a session variable in a <a href> over to the next page?

Please can someone help me with this. I have this MySQL query which lists users on my site, and echos a link that can be clicked to take you to the user's profile:
<?php
$online_set = online_channel();
while ($online = mysql_fetch_array($online_set)) {
echo "<div class=\"online_row\"><img width=25px height=25px src=\"data/photos/{$online['user_id']}/_default.jpg\" class=\"online_image\"/><div class=\"online_text\">{$online['display_name']}</div></div>";?>
<? } ?>
The link goes to profile.php and echos the users 'user_id' so it knows which users profile to take you to, and now I am wanting to include a session variable in the link somehow so a message is displayed on that users profile after clicking the link.
I have tried including $_SESSION['chat'] in the link but it doesn't work:
<?php
$online_set = online_channel();
while ($online = mysql_fetch_array($online_set)) {
echo "<div class=\"online_row\"><img width=25px height=25px src=\"data/photos/{$online['user_id']}/_default.jpg\" class=\"online_image\"/><div class=\"online_text\">{$online['display_name']}</div></div>";?>
<? } ?>
I am also trying to execute the session in profile.php by using this:
<?
session_start();
if(isset($_SESSION['chat']))
echo $_SESSION['chat']="<div class=\"infobox-favourites\"><strong>Deleted from Favourites</strong> - This user has successfully been deleted from your favourites.</div><div class=\"infobox-close4\"></div>";
unset($_SESSION['chat']);
?>
What I have tried is not working and i'm not sure i'm doing it right, so I would really appreciate any help with this. Thanks
Try this...for easier debugging the entire code you have
<?php
$online_set = online_channel();
while ($online = mysql_fetch_array($online_set)) {
?>
<div class="online_row">
<a href="profile.php?id=<?php echo $online['user_id'];?>">
<img width=25px height=25px src="data/photos/<?php echo $online['user_id'];?>/_default.jpg/" class="online_image" />
<div class="online_text\">
<?php echo $online['display_name'];?>
</div>
</a>
</div>
<?php
}
?>
Just review the code I posted to learn the better way to echo an entire div

Output Name in PHP From mysql Database

I have a list of names in a database that i want to display one by one
(also for bonus points, another column in the database is a Boolean value for if a task is completed or not. if this is true i want the css content box background to be green instead of red.)
so how can i select a name from row one, put it to a PHP variable, then select the value from the "Name" column in row 2 and put that to another PHP variable or the next item in the array?
thanks for any help!
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="mngPWinCSS.css"/>
</head>
<body>
<?php
$dsn ='mysql:host=****.******.com;dbname=o****_**n';
$username='********';
$password ='******';
mysql_connect('localhost',$username,$password);
$query=mysql_query("SELECT Name FROM CLOAS_Team LIMIT 0,1");
$bob="dkajfk";
$url=$_SERVER['REQUEST_URI'];
header("Refresh: 60; URL=$url");
$com[1]="i";
$com[2]="i";
$com[3]="i";
$com[4]="i";
$com[5]="i";
$com[6]="i";
$name=mysql_fetch_array($query);
?>
<div id="content">
<img src="logjpg.JPG" alt="Smiley face" height="50" width="200">
<h3>CLOAS Tracker</h3>
</div>
<div id="Content">
<?php
?>
<div id="complete">
<h3names>
<?php
echo $name['Name'];
?>
</h3names>
</div>
<div id="incomplete">
<h3names>Name2</h3names>
</div>
</div>
</body>
</html>
First you need to change your SELECT query to select all of the rows that you wish to display, perhaps by taking off the LIMIT clause. Something like this;
$result=mysql_query("SELECT Name FROM CLOAS_Team");
(This will get you all of the names in your table.)
Next, you need to loop through the results you got from this query, like so;
$names = array();
while($row = mysql_fetch_assoc($result))
{
$names[] = $row['Name'];
}
This will put them into the array $names for you, which you can then work with. Instead of putting them into the array, you might want to output them immediately, perhaps like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div>
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>
However, you have many more errors in your code. Such as;
You can't just invent html elements called <h3names>
I doubt that you want to set the id attribute to 'incomplete'. An id should be unique, I expect you should be putting this in as a class (class = "incomplete")
I don't think your line header("Refresh: 60; URL=$url"); will do anything as your headers have already been sent to the page. If you want this line to work, it needs to be right at the top, BEFORE any output has been sent to the browser.
And for the bonus point, include the 'Completed' field in your query (if that is what it is called) and use this to add a style to each <div> element that you display in your loop. So your query might become;
$result=mysql_query("SELECT Name, Completed FROM CLOAS_Team");
And your loop would now be like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div style = "background-color:<?php echo $row['Completed'] == true ? 'green' : ' red'; ?>">
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>

Categories