Membership with Facebook (Error: MySql) - php

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')")

Related

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.

Php MySQL updating a column only if IP is new

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)");

How do I put multiple PHP commands in one?

How can I put multiple php commands like:
$email = $_POST['email'];
//get the user.id
$result = mysql_query("SELECT user.id FROM user WHERE user.email LIKE '$email'");
$user_id = mysql_fetch_array($result);
$user_id = $user_id["id"];
//fill the album -> "Profilbilder"
mysql_query("INSERT INTO `album` (`user_id`, `name`) VALUES ('$user_id', 'Profilbilder')") or die(mysql_error());
//get the album.id
$result = mysql_query("SELECT album.id FROM album WHERE album.user_id = '$user_id'");
$album_id = mysql_fetch_array($result);
$album_id = $album_id["id"];
mysql_query("INSERT INTO `foto` (`album_id`, `name`, `zeitstempel`, `link`) VALUES ('$album_id', '$file_name', NOW(), '$file_path')") or die(mysql_error());
.. to get database information in one big command?
You can actually insert into a table the results from a query like so:
$query="INSERT INTO `album`
(`user_id`, `name`)
SELECT user.id, 'Profilbilder'
FROM `user`
WHERE user.email LIKE '%$email%'";

Use returned ID from SCOPE_IDENTITY in new Query

Right now, this is what I have:
$query = "INSERT INTO COMMENTS VALUES ('$user', '$comment', '$star')";
mssql_query($query, $connection);
$commentIDQuery = "SELECT SCOPE_IDENTITY() AS ins_id";
$CI = mssql_query ($commentIDQuery, $connection);
$commentID = mssql_fetch_row($CI);
$idQuery = "SELECT recipeid FROM t_recipe WHERE recipename = '$recipeName'";
$RID = mssql_query($idQuery, $connection);
$recipeID = mssql_fetch_row($RID);
$rcQuery = "INSERT INTO COMMENT_RECIPE VALUES ('$commentID[0]', '$recipeID[0]')";
mssql_query($rcQuery, $connection);
So how would I get that ins_id?
It adds it to the first table, which is comments, but not the relation table.
Using sql server 2008
What about this......
$query = "DECLARE #NewID INT
INSERT INTO COMMENTS VALUES ('$user', '$comment', '$star');
SELECT #NewID = SCOPE_IDENTITY();
INSERT INTO COMMENTS_RECIPE VALUES (#NewID, '$recipeid')";
$stmt = sqlsrv_query($conn,$query);

add mysql row if userID do not exist in table

i'm sending a post request to this code:
$name = (string)$_POST['name'];
$id = (int)$_POST['id'];
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
Which works fine and it adds a row to the table. How do i check wether the userID all ready exist in one of the following rows?
Do it like this
$query = "SELECT COUNT(*) FROM Users WHERE userID = '$id'";
$result = mysqli_query($link,$query);
if ( mysqli_fetch_assoc($result) ) {
$message = "Already exists";
} else {
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
}
Try this
$name = (string)$_POST['name'];
$id = (int)$_POST['id'];
$res = mysqli_query($link, "SELECT * FROM Users WHERE userID = '$id' LIMIT 1 ");
if($row = mysqli_fetch_assoc($res))
{
echo "this user id is already exists";
}
else
{
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
echo "record inserted successfully ";
}
REMEMBER : always use LIMIT 1 when you trying to get exactly one result.
IF you have properly set 'id' as primary key or unique key in your table, you can use the modifier IGNORE in your query you don't get an error when you try to isert a duplicate.
Doing this will result in the row only being inserted if the value of the primary key wasn't already in the table.
$query = "INSERT IGNORE INTO Users (name, userID) VALUES ('$name', '$id')";
IF you haven't set a primary key in your table you will have to do a SELECT query to find out if a row with that id is already in your table.
Make the UserID an Unique Key.
If it already exists, your code will throw an error and the row will not be insterted.
alter table Users
add unique index Unique_user (userID (8000))
Before inserting the values to the table check whether the following user id exists in the table or not
You can do it in this way
$name = $_POST['name'];
$id = $_POST['id'];
$sql = "SELECT * FROM Users WHERE userID = '$id'";
$res= mysqli_query($sql);
$num = mysqli_num_rows($res);
if($num == 0)
{
$query2 = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result2 = mysqli_query($query2);
echo "record inserted successfully ";
}
else
{
echo "Record Failed !!";
}

Categories