Php MySQL updating a column only if IP is new - php

I'm trying to make my script update the view count by +1 everytime a IP is new.
and after 604800 seconds, if the same user(same IP) comeback again after 604800 seconds view count by+1.
Can someone help me out here.
//Get video id
$id = $_GET['id'];
//Get video title
$videoName = $_GET['idtitle'];
//Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=videodb', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Get user IP
$ip = $_SERVER["REMOTE_ADDR"];
//Insert that user IP, Name, Title and increase view count by +1
//This is what i want to accomplish but is not working!
$insert = $pdo->query("INSERT INTO `videodb`.`videos` ( `ip`, `name`, `title`, `views`) VALUES ('$ip', '$id', '$videoName', `views`+1)");
// Sample Two
//Select the IP from videos
$select = $pdo->prepare("SELECT `ip` FROM `videos`");
$sql = $select->execute();
while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
//If the IP in database is not equal to the user IP in database views +1
if($row->fetch('ip') == $ip){
$pdo->query("UPDATE videos SET `views` = `views`+1 WHERE id = '$id' ");
}}

Add one more column in your table as last_viewed_at DATETIME.
Now before inserting the record into the database:
As you are checking the the record for the last 7 days then query as like below:
$row = "SELECT * FROM videos WHERE
id = 'users.ip.to.check'";
Conditions: You have got record against the users.ip.to.check
now check whether the time difference is more than 7 days.
means.
if (count($row) > 0) {
$ipLastViewAt = new \DateTime($row['last_viewed_at']);
$currentDate = new \DateTime();
$diff = $currentDate->diff($ipLastViewAt)->format("%a");
if ($diff >= 7 ) {
// update the record with the view + 1 and with last_view_at = currentDateTime;
}
} else {
// Insert the record with the view +1 and with last_view_at = currentDateTime;
}

If Ip is unique field then this query should help
INSERT INTO `videodb`.`videos`( `ip`, `name`, `title`, `views`) VALUES ('$ip', '$id', '$videoName', 1) ON DUPLICATE KEY UPDATE `views`=views+1;

is not a full code,just for your information!
Tips:two tables maybe better,one save video info,another save visitor info
videos:id,ip,name,title,views,update_time
// first, select $video info and get the result --- "select * from videos where ip='{$ip}' and id='{$id}'";
// we got $video look like : array('id'=>1,'update_time'=>'1453970786')
$time = time();
if( isset($video['id']) && (($time - $video['update_time']) >= 604800) ){
$pdo->query("UPDATE `videodb`.`videos` SET `views`=`views`+1 AND update_time='$time' WHERE id = '$id'");
}elseif( !isset($video['id']) ){
$pdo->query("INSERT INTO `videodb`.`videos`( `ip`, `name`, `title`, `views`) VALUES ('$ip', '$id', '$videoName', 1)");
}
edit
$pdo->query("INSERT INTO `videodb`.`videos`(`id`, `ip`, `name`, `title`, `views`) VALUES ('$id','$ip', '$id', '$videoName', 1)");

Related

(Php)Retrieve primary key of previous table and insert into current table

Im new to php scripting.. I want to know if there is any mistake in my php script that i want to fetch income_id (primary key in income table) from income table and insert it into expenses table(as foreign key)...I able to add all data into expenses table except the income_id..
<?php
//Importing our db connection script
require_once('dbConnect.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$id = $_POST['id'];
$income_id = $_POST['income_id'];
$category = $_POST['category'];
$amount = $_POST['amount'];
$date = date('Y-m-d');
$sql = "SELECT income_id from `income` where id='".$id."'";
$result = mysqli_query($con, $sql);
$rows = mysqli_fetch_array($result);
//Creating an sql query
$sql = "INSERT INTO expenses (income_id,category,amount,date) VALUES ('$rows[income_id]','$category','$amount','$date')";
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Added Successfully';
}else{
echo 'Could Not Add';
}
//Closing the database
mysqli_close($con);
}
I would suggest joining both queries:
INSERT INTO expenses (income_id, category, amount, date)
VALUES ((SELECT income_id FROM `income` WHERE id='$id'), '$category', '$amount', '$date')

UPDATE table record instead of adding a new record MySQL

Ok .. Here is the thing. I want to list users logged on and change their status when logged out. This works perfect. I created a table for that called tblaudit_users. The existing users I SELECT from a tbl_users table.
What I want, is that if an user already exists in the tblaudit_users table it will UPDATE the LastTimeSeen time with NOW(). But instead of updating that record, it creates a new record. This way the table will grow and grow and I want to avoid that. The code I use for this looks like:
+++++++++++++++++++
$ipaddress = $_SERVER['REMOTE_ADDR'];
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' AND active = '1' LIMIT 1");
$query->execute();
foreach($query->fetchAll(PDO::FETCH_OBJ) as $value){
$duplicate = $value->username;
}
if($duplicate != 1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($duplicate = 1){
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE username = '{$username}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
I am lost and searched many websites/pages to solve this so hopefully someone here can help me? Thanks in advance !!
UPDATE:
I've tried the below with no result.
+++++
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
Ok. I altered my query and code a little:
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' LIMIT 1");
$query->execute();
if($query){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
} else {
header('Location: index.php');
die();
}
}
I also added a UNIQUE key called pid (primary id). Still not working.
Base on http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html, don't use 'set' in update syntax
example from the page:
INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=9;
Several issues:
You test on $query, but that is your statement object, which also will be valid even if you have no records returned from the select statement;
There can be issues accessing a second prepared statement before making sure the previous one is closed or at least has all its records fetched;
There is a syntax error in the insert statement (set should not be there);
For the insert ... on duplicate key update to work, the values you provide must include the unique key;
SQL injection vulnerability;
Unnecessary split of select and insert: this can be done in one statement
You can write your test using num_rows(). To get a correct count call store_result(). Also it is good practice to close a statement before issuing the next one:
$query = $db->prepare("SELECT * FROM tblaudit_users
WHERE username = '{$username}' LIMIT 1");
$query->execute();
$query->store_result();
if($query->num_rows()){
$query->close();
// etc...
However, this whole query is unnecessary when you do insert ... on duplicate key update: there is no need to first check with a select whether that user actually exists. That is all done by the insert ... on duplicate key update statement.
Error in INSERT
The syntax for ON DUPLICATE KEY UPDATE should not have the word SET following it.
Prevent SQL Injection
Although you use prepared statements (good!), you still inject strings into your SQL statements (bad!). One of the advantages of prepared statements is that you can use arguments to your query without actually injecting strings into the SQL string, using bind_param():
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district,
gemeente, ipaddress, LastTimeSeen, status)
VALUES (?, ?, ?, ?, ?, ?, NOW(), '1')
ON DUPLICATE KEY UPDATE LastTimeSeen = NOW(), status = '1'
");
$insert->bind_param("ssssss", $userId, $username, $achternaam,
$district, $gemeente, $ipaddress);
$insert->execute();
This way you avoid SQL injection.
Make sure that user_id has a unique constraint in the tblaudit_users. It does not help to have another (auto_increment) field as primary key. It must be one of the fields you are inserting values for.
The above code no longer uses $query. You don't need it.
I found the issue
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE user_id = '{$userId}' LIMIT 1");
$query->execute();
if($query->rowcount()<1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($query->rowcount()>0) {
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE user_id = '{$userId}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
Instead of using $username in my query, I choose $userId and it works.

can't insert the same data into 2 tables at the same time in php mysql

I need your help to fix my problem..
first I have 2 tables in mysql dbase.. here are the structures :
doctor1:
--------
no_que autoincrement pk,
doctor_name,
id_patient,
date,
time
status_que:
----------
id_patient,
doctor_name,
no_que fk,
date,
time
I want to insert data into doctor1 and the data will be the same at status_que..
$idp=$_POST['id_patient'];
$dt=$_POST['date'];
$tm=$_POST['time'];
$dn=$_POST['doctor_name'];
$query = "INSERT INTO doctor1 (doctor_name, id_patient, date, time)
values ('$dn', '$idp', '$dt', '$tm')";
$result = #mysql_query($query) or die("REPORT Failed to save data.");
$last_insert_no_que = mysql_insert_id();
#query2 = "INSERT INTO status_queue (id_patient, doctor_name, no_que, date, time)
values ('$idp', '$dn', '$last_insert_no_que', '$dt', '$tm')";
$result = #mysql_query($query2) or die("REPORT Failed to save data.");
but that code doesn't work
it works ! I only have to delete "#" operator.. :) ~ thx you
so here is my code :
$idp=$_POST['id_patient'];
$dt=$_POST['date'];
$tm=$_POST['time'];
$dn=$_POST['doctor_name'];
$query = "INSERT INTO doctor1 (doctor_name, id_patient, date, time)
values ('$dn', '$idp', '$dt', '$tm')";
$result = mysql_query($query) or die(mysql_error());
$last_insert_no_que = mysql_insert_id();
$query2 = "INSERT INTO status_queue (id_patient, doctor_name, no_que, date, time)
values ('$idp', '$dn', '$last_insert_no_que', '$dt', '$tm')";
$result = mysql_query($query2) or die(mysql_error());
>

Membership with Facebook (Error: MySql)

Facebook and Twitter membership script error:
(does not record data to the database)
Login=>FB/TW DATABASE=>CONNECT OK!=>BACK TO MY WEBSITE=>MY DATABASE=>ERROR
SQL:
CREATE TABLE users
(
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(70),
oauth_uid VARCHAR(200),
oauth_provider VARCHAR(200),
username VARCHAR(100),
twitter_oauth_token VARCHAR(200),
twitter_oauth_token_secret VARCHAR(200)
);
loginFacebook.php:
<?php
require 'dbconfig.php';
class User {
function checkUser($uid, $oauth_provider, $username,$email,$twitter_otoken,$twitter_otoken_secret)
{
$query = mysql_query("SELECT * FROM `users` WHERE oauth_uid = '$uid' and oauth_provider = '$oauth_provider'") or die(mysql_error());
$result = mysql_fetch_array($query);
if (!empty($result)) {
# User is already present
} else {
#user not present. Insert a new Record
$query = mysql_query("INSERT INTO `users` (oauth_provider, oauth_uid, username,email,twitter_oauth_token,twitter_oauth_token_secret) VALUES ('$oauth_provider', $uid, '$username','$email')") or die(mysql_error());
$query = mysql_query("SELECT * FROM `users` WHERE oauth_uid = '$uid' and oauth_provider = '$oauth_provider'");
$result = mysql_fetch_array($query);
return $result;
}
return $result;
}
} ?>
Screen: Error
Column count doesn't match value count at row 1
What's wrong?
best regards,
Reformatted your query to be on multiple lines for readability:
$query = mysql_query(
"INSERT INTO `users`
(oauth_provider, oauth_uid, username, email, twitter_oauth_token, twitter_oauth_token_secret)
VALUES
('$oauth_provider', $uid, '$username','$email')
"
) or die(mysql_error());
You are specifying 6 columns in your INSERT statement, but only supplying 4 actual values for these columns. Either remove the last 2 twitter_oauth_* columns from your query, or supply the values for these columns.
What you have is
INSERT INTO `users` (oauth_provider, oauth_uid, username, email, twitter_oauth_token, twitter_oauth_token_secret)
VALUES ('$oauth_provider', $uid, '$username','$email')")
As you see you are trying to insert 6 values, however in query you are providing data of only 4 items ('$oauth_provider', $uid, '$username','$email'), it is showing error.
Below are two ways use you can use depending on the requirement you have.
Option 1
INSERT INTO `users` (oauth_provider, oauth_uid, username, email, twitter_oauth_token, twitter_oauth_token_secret)
VALUES ('$oauth_provider', $uid, '$username','$email',NULL, NULL)")
OR Option 2
INSERT INTO `users` (oauth_provider, oauth_uid, username, email)
VALUES ('$oauth_provider', $uid, '$username','$email')")

Update FK from PK using PHP-MySQL

i'm new in php and mysql
i have a problem
i have 2 tables
<?php
$insert = mysql_query("INSERT INTO request (date, type_request, subject, customer)
VALUES (NOW(), '".$type."', '".$subject."', '".$username."')");
$fk = mysql_query("insert into feedback (id_request) select id_request from request where id_request = last_insert_id ");
?>
i've been doing that but still cannot fill the id_request in table feedback
the structure of table is like this
Table Request
id_request auto_increment not_null,-->PK
date,
type_request,
subject,
customer
Table Feedback
id_feedback auto_increment not_null,
id_request,---FK
feedback_user
can anyone give suggest how to update the foreign key
Regards
In your code
$fk = mysql_query("insert into feedback (id_request) select id_request from request where id_request = last_insert_id ");
replace last_insert_id with LAST_INSERT_ID()
since its a MySQL function and not a field.
I know I will get flamed for this, but this is how I would do it:
<?php
$date = date('Y-m-d H:i:s');
$req_query = 'INSERT INTO request (date, type_request, subject, customer) '.
"VALUES ('$date', '$type', '$subject', '$username')";
$req_result = mysql_query($req_query);
$fk_query = 'SELECT MAX(id) id FROM request '.
"WHERE date = '$date' AND type_request = '$type' ".
"AND subject = '$subject' AND customer = '$username'";
$fk_result = mysql_query($fk_query);
$fk_row = mysql_fetch_assoc($fk_result);
$fk = $fk_row['id'];
$fb_result = mysql_query("INSERT INTO feedback (id_request) VALUES($fk)");
?>

Categories