I'm trying to create analytic data for each of the User Profiles by telling them how many visitors visited from city & country visited their profile.
This is what I'm currently doing.
session_start();
$analyticsuser = $_SESSION["analyticsuser"];
if($analyticsuser!=$author) //$author is where the id of each profile is stored.
{
$ip = $_SERVER['REMOTE_ADDR'];
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success')
{
$userip = $query['query'];
$usercountry = $query ['country'];
$usercity = $query['city'];
$connection = mysqli_connect("HOSTNAME","USERNAME","PASSWORD","leo_site") or die("Error " . mysqli_error($connection));
$sqlanalytics = "INSERT INTO member_analytics VALUES(NULL,\"$userip\",\"$author\",\"$usercity\",\"$usercountry\",now());";
$resanalytics = mysqli_query($connection, $sqlanalytics) or die("Error " . mysqli_error($connection));
}
else { echo 'Unable to get location'; }
}
$_SESSION["analyticsuser"] = $author;
I'm trying to get how many visitors visited their profile from different city & countries.
The problem I'm facing now is, if I visit a profile again after visiting another profile, the data is still recorded. This should not happen as we have already recorded the visitor for that profile.
There are so many ways to solve this issue, one of them which I mostly used is an feature of mysql.
First create a composite key using author and userip.
After that at place of insert run replace query. As per nature of replace query if its find same author and userip combination field it replace that row by new data and if there is no combination found it will insert it.
$sqlanalytics = "REPLACE INTO member_analytics VALUES(NULL,\"$userip\",\"$author\",\"$usercity\",\"$usercountry\",now());";
I have solved my problem, You have to read session ID to check everytime if a profile is already visited by a visitor.
Below is the correct code.
session_start();
$new_sessionid = session_id();
$connection = mysqli_connect("HOSTNAME","USERNAME","PASSWORD","leo_site") or die("Error " . mysqli_error($connection));
$sqlcanalytics = "SELECT * FROM member_analytics WHERE sessid=\"$new_sessionid\" AND uid=\"$author\";";
$rescanalytics = mysqli_query($connection, $sqlcanalytics) or die("Error " . mysqli_error($connection));
$numcanalytics = mysqli_num_rows($rescanalytics);
if($numcanalytics==0)
{
$ip = $_SERVER['REMOTE_ADDR'];
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success')
{
$userip = $query['query'];
$userisp = $query['isp'];
$organization = $query['org'];
$usercountry = $query ['country'];
$userregion = $query['regionName'];
$usercity = $query['city'];
$sqlanalytics = "INSERT INTO member_analytics VALUES(NULL,\"$userip\",\"$author\",\"$new_sessionid\",\"$usercity\",\"$usercountry\",now());";
$resanalytics = mysqli_query($connection, $sqlanalytics) or die("Error " . mysqli_error($connection));
}
else { echo 'Unable to get location'; }
}
Thanks for the help!
Related
I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.
I keep getting a 'Resource id # 6' failure when submitting a script on my website. The code I'm using is the same type of code I use for registering for the website and that works but this script doesn't work at all. What my code does is send a booking request with the fields as shown to the database. I keep getting a Resource id#6 error , and I've googled what that is but I can't seem to figure out whats wrong. I am a beginner at php , so any tips on whats to look for to avoid a resource id # 6 error would be a lot of help
<?php
//$pattern="/^.+#.+/.com/";
//error_reporting(0);
if(isset($_POST["submit"])){
$Name_of_Person = $_POST['Name_of_Person'];
$Name_of_Group = $_POST['Name_of_Group'];
$room = $_POST['room'];
$How_Many_People = $_POST['How_Many_People'];
$Date_of_Booking = $_POST['Date_of_Booking'];
$End_time = $_POST['End_time'];
$Purpose = $_POST['Purpose'];
$Contact_Number = $_POST['Contact_Number'];
$Contact_Email = $_POST['Contact_Email'];
$Alcohol = $_POST['Alcohol'];
$Security = $_POST['Security'];
$Projector = $_POST['Projector'];
$Extra_Chairs = $_POST['Extra_Chairs'];
$Extra_Info = $_POST['Extra_Info'];
$Activated = '0';
$con = mysql_connect('localhost','root','test123') or die("couldn't connect");
mysql_select_db('bookerdb') or die("couldn't connect to DB");
//if(filter_var($email, FILTER_VALIDATE_EMAIL)){//(preg_match($pattern, $_POST['Contact_Email'])){
$query = mysql_query("SELECT * FROM `booking_table` WHERE Date_of_Booking='".$Date_of_Booking."' AND room='".$room."'");
$numrows = mysql_num_rows($query);
echo $query;
if($numrows==0){
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
$result = mysql_query($sql);
if($result){
echo "Sent to be approved";
$redirect_page = '../ASC.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}else{
echo "Failed";
}
}else{
echo"There is already a requested booking on that date & time";
$redirect_page = '../EAR.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}
/*}else{
echo "error";
$redirect_page = '../EWF.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}*/
}
?>
You have error in your second SQL query. You try to insert 14 values into 15 columns (in values you forgot $Contact_Email).
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Contact_Email','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
Than remove echo $query from your code, line 30.
In $query isn't query, but mysql result object. You can't work with that by this way, you can't echo it.
I'm pretty new to both PHP and MySQL and I'm struggling to get my login system to function properly. The registration works fine, but when I run the login it doesn't recognise there is anything within the table matching the entered data. Below is the code I believe to be the problem area.
Thanks in advance.
<?php
function load($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].
dirname($_SERVER['PHP_SELF']);
$url = rtrim($url,'/\/');
$url.= '/'.$page;
header("location:$url");
exit();
}
function validate($dbc,$email ='',$pwd='')
{
$errors = array();
if (empty($email))
{ $errors[] = 'Enter your email address.'; }
else
{ $e = mysqli_real_escape_string($dbc,trim($email));}
if (empty($pwd))
{ $errors[] = 'Enter your password.';}
else
{ $p = mysqli_real_escape_string($dbc, trim($pwd)); }
if (empty($errors))
{
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1)
{ $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array( true, $row);}
else
{$errors[]='Email address and password not found.';}
}
return array(false,$errors);
}
I believe that you'll get what you're looking for if you change
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
to
$p = SHA1($p);
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = '$p'";
Whenever a PHP-to-MySQL query isn't performing as expected, my first step is to get a look at the SQL I'm actually passing to the database. In this case, it would be by inserting a line like echo '<p>$q</p>'; immediately after assigning the value of $q.
Sometimes it immediately becomes obvious that I've got a malformed query just by looking at it. If it doesn't, I copy the SQL code that appears and run it as a query within the database manager, to see what errors it throws and/or examine the resulting data.
<?php
session_start();
$host = 'localhost';
$user = 'root';
$password = '8******8';
$database = 'tg*****ba';
$conn = mysql_connect($host,$user,$password) or
die('Server Information is not Correct');
//Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
$InGameName = mysql_real_escape_string($_POST['InGameName']);
$LastVoteTime;
//===When I will Set the Button to 1 or Press Button to register
if(isset($_POST['btnVote']))
{
if(md5($_POST['code']) != $_SESSION['key'])
die("You've entered a wrong code!");
$query = mysql_query("SELECT * FROM entities WHERE Name = '". $InGameName ."'");
if (mysql_num_rows($query) < 0)
{
die("This In game name doesn't exist , please enter your account name not username!");
}
else
{
$date = date('YmdHis');
$row=mysql_fetch_object($query);
$lastvote=$row->LastVoteTime;
$votingpoints = $row->VotsPoints;
$url = "http://www.xtremetop100.com/in.php?site=***********";
if(($lastvote + 120000) < $date)
{
$lastvote = $date;
$votingpoints += 1;
$query = mysql_query("update entities set VotsPoints ='$votingpoints' set LastVoteTime ='$lastvote' WHERE Name = '". $InGameName ."'");
}
else
die("You've Already voted in the last 12 hrs!");
}
}
?>
It does not update the database with the votingpoints and lastvotetime
however it pass the first check (which means it found the account record in the database) but it doesn't set them in the end of that code
thanks in advance
Try:
$query = mysql_query("update entities set VotsPoints = '$votingpoints', LastVoteTime = '$lastvote' WHERE Name = '". $InGameName ."'");
You're using "set" multiple times, not sure if that's ok.
Your SQL syntax is incorrect on the UPDATE statement.
http://dev.mysql.com/doc/refman/5.0/en/update.html
I am getting an error message in my php query.
Error being displayed:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1294251744','127.0.0.1','/register')' at line 2
my code:
<?php
require_once("includes/database.php");
//Set timeout to 5 minutes
$timeoutseconds = 300 ;
//get the time
$timestamp = time();
//Delete all users that are no online after the time out allowed
$timeout = $timestamp - $timeoutseconds ;
// stores users IP addresss
$user_ip = $_SERVER['REMOTE_ADDR'];
// Automatically collects the hostname or domain like example.com)
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/');
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES (''$timestamp','$user_ip','$path')";
$result = mysql_query($sql, $conndb) or die(mysql_error());
//delete values when they leave
mysql_query("DELETE FROM totalonline WHERE timestamp < $timeout");
//grab the results
$sql = "SELECT DISTINCT ip FROM totalonline WHERE file='$path' ";
$result = mysql_query($sql, $conndb) or die(mysql_error());
//number of rows = the number of people online
$user = mysql_num_rows($result);
//spit out the results
if( $user == 1 ) {
echo "$user User online";
} else {
echo "$user User online";
}
?>
Change this:
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES (''$timestamp','$user_ip','$path')";
to this:
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES ('$timestamp','$user_ip','$path')";
You had two single quotes instead of one.
Also, near the end, you probably want to change this:
if( $user == 1 ) {
echo "$user User online";
} else {
echo "$user User online";
}
to this:
if( $user == 1 ) {
echo "$user User online";
} else {
echo "$user User offline";
}
You have double ' in the values field;)
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES (''$timestamp','$user_ip','$path')";
Right before $timestamp.
It's better to do
//insert the values
$sql = 'INSERT INTO totalonline(timestamp, ip, file)
VALUES ('.$timestamp.',"'.$user_ip."',"'.$path.'")';
because that way you make sure the db understands ip and path are strings.