Like system In Php - php

Hey I want to create like system in php But I am facing some problem on it ...
How can I create Like system that allow only one like per one user??
This is my code
<?php
if(isset($_POST['like'])){
$q = "SELECT * FROM likes WHERE `username` = '".$_SESSION['recieveruser']."'";
$r = mysqli_query($con, $q);
$count = mysqli_num_rows($r);
if ($count == "0") {
$q1 = "INSERT INTO likes (`username`, `likecount`)VALUES('".$_SESSION['recieveruser']."', '1')";
$result1 = mysqli_query($con, $q1);
} else {
while($row = mysqli_fetch_array($r)) {
$liked = $row['likecount'];
}
$likeus = ++$liked;
$q2 = "UPDATE likes SET likecount='".$likeus."' WHERE username = '".$_SESSION['recieveruser']."'";
$result2 = mysqli_query($con, $q2);
}
}
give me some suggestions
I want only one like per user
In this code every user can give Many likes to another user but I want only one like per one user and I want to display the name of the user who gave like if it's possible
This is only user like code...

I created simliar like system on my website. In my likes table, I had these columns:
Id of comment, that has been liked
Id of user who liked
Id of like (for removal)
When user clicked like, I inserted new row into likes table, with two known values. ID of like was autoincremented.
To show number of likes, I filtered by id of comment and grouped by users id (just to be sure). The number was obtained using count.
select count(*) from likes where comment_id = 666 group by user_id;
Even if you let user insert multiple times, the like counts only as one. But best would be to check, if current user already liked and dont let him do that. For this task, insert on duplicate key update could be used, to spare if exists db request (select).

You should not use the code you posted above. First of all, your code is vulnerable to SQL-Injections and therefore you should use Prepared Statements (https://www.php.net/manual/de/mysqli.quickstart.prepared-statements.php). Second, $_SESSION variables are depricated (https://www.php.net/manual/en/reserved.variables.session.php).
Lets assume you want users only to be able to like a post once. Then, instead of the column likecount you would need a post-id which uniquely identifies the post.
Define the combination post-id and username as a primary key in your database.
Now your code just have to check whether you find the username with the according post-id in the table likes.
In case you do not find the username with the according post-id in the table, you have to INSERT the username and the post-id

Related

MYSQL spillover function

I am currently trying to code a Networking website and am stuck at the spillover function stage.Here is how it works, each registered user of the site is only allowed to refer two people into the network (they have a referral link for this). If however,a member gave his/her link to refer more than two people and the registering folk wants to sign up with the link,the following event should occur:
1. PHP should query MYSQL Database to ascertain if the sponsor has referred up to two(2) people, if YES then MYSQL will search for a random sponsor-username to replace the initial sponsor .
2. If on the contrary,MYSQL checks and found that the sponsor hasn't referred two people yet, then MYSQL will proceed to using the sponsor username for the new registering member.
Below is what the database table looks like:
My MYSQL database snapshot
The table name is affiliateuser, the referedby column is where the sponsors are shown for each member,i need member to only be able to appear as sponsor twice (maximum) under the referedby column.
Looking at the table above,the user yelefash2 has referred two people with his link while user mipe305 hasnt referred anyone with his link or username,i need to set a balance and if a third person tries to register with yelefash2's username/referral link,let PHP/MYSQL replace him with a user who hasnt referred two people yet (it could be random pick or otherwise), this will spill over members automatically as referrals onto available spaces, e.g mipe305
I have tried the following PHP codes but it doesn't work:
$ref=mysqli_real_escape_string($con,$_POST['referral']);//data from the referrer webform field//
$result = mysqli_query($con,"SELECT count(*) FROM affiliateuser where username = '$ref'");
$row = mysqli_fetch_row($result);
$numrows = $row[0];
if ($numrows==0)
{
$msg=$msg."Sponsor/Referral Username Not Found..<BR>";//for checking if provided sponsor exits
$status= "NOTOK";
}
$reea = mysqli_query($con,"SELECT username,referedby, COUNT(username) FROM affiliateuser GROUP BY referedby ASC");
$reeeb = mysqli_query($con,"SELECT count(*) FROM affiliateuser where referedby='$ref' ");
$row = mysqli_fetch_row($reeeb););
$refcount = $rowp[0];
if ($refcount ==2 OR $refcount >2)
{$reee = mysqli_query($con,"SELECT username,referedby, COUNT(username) FROM affiliateuser GROUP BY referedby ASC");
$reeel = mysqli_query($con,"SELECT referedby FROM affiliateuser where COUNT(username)<2 ");
$row = mysqli_fetch_row($reeel);
$refpick = $row[0];
}
else
{$refpick=mysqli_real_escape_string($con,$_POST['referral']);}
I know i must be doing something wrong,am kinda new to MYSQL and PHP, any help would be pretty much appreciated
Changed my awnser:
$reea = mysqli_query($con,"SELECT username,referedby, COUNT(username)
FROM affiliateuser GROUP BY referedby ASC");
is not doing anything.but it could be something going somewhere else in the page and its not in this post.
but your result array variable is wrong.
$refcount = $rowp[0];
should be
$refcount = $row[0];
because $rowp is not defined anywhere.... also its row result:
$row = mysqli_fetch_row($reeeb););
is wrong. it should be:
$row = mysqli_fetch_row($reeeb);
at the end, the else condition:
{$refpick=mysqli_real_escape_string($con,$_POST['referral']);}
can be simplified by:
{$refpick=$ref;}
One thing about comparing,
the if ($refcount ==2 OR $refcount >2) should work,
but if (($refcount ==2) OR ($refcount >2)) will guarantee the correct operation.
I personally use || (double pipe) instead of "or" personally.
so I would have wrote it as: if (($refcount ==2) || ($refcount >2)) {

Making php script run multiple times

I have a system where a PHP script uses MySQL to get info based on a user. Then, based on that information, a certain button will be displayed. The database that is being called has columns:
id
user_one
user_two
This is meant to check if two users are friends. However, my problem is that if a user has more that 1 friend the script only works for the 1st friend.
$select_friends_query = mysql_query("SELECT friend_id FROM friends WHERE user_id = '$user'");
while($friend_row = mysql_fetch_assoc($select_friends_query)) {
$friend = $friend_row['friend_id'];
}
if ($username == $friend) {
$addAsFriend = '<input type="submit" class = "frnd_req" name="removefriend" value="Disassociate">';
}
else
{
$addAsFriend = '<input type = "submit" class = "frnd_req" name = "addfriend" value = "Send Associate Request">';
}
}
}
Then I have echo $addAsFriend later.
I recommend that you change your database design as follows:
User_id, PK
Friend_id, PK
PK = Primary Key. Primary key is the key under which records are stored. It must be unique. The reason we are making it a COMPOUND primary key (two fields make up the PK instead of 1) is because it is impossible for a user to be friends with with the same user Multiple times. Mysql will ensure this does not happen and you won't have to do it on the application level.
Thus, if user "12" and user "25" become friend you should two records:
(12, 25) and (25, 12)
You must have two records because data means literally "user this has friend that." Is it possible for two users to have a one way friendship - not really BUT you may want to one day expand this table to include preferences on the relationship type between the two friends and you would want to distinguish between A -> B and B -> A relationship.
So let's get to the meat of the question. To query mysql to find all friends to a specific user we do the following:
$sql = "SELECT friend_id FROM friends WHERE user_id = 25;";
$query = mysql_query($sql, $connection);
// Loop through all friend records
while ($row = mysql_fetch_assoc($query)) {
$friends[$row['friend']];
}
I don't use procedural code (mysql_query) and instead use mysqli with OP: $mysql->query(). basically, I am not 100% sure if this code will run but it gives you a guide to get started.
At the end of the program, you will have an array "friends" with keys that tell you the friend ids. So "friends" -> 12, 21 could be a potential data set.
You have to look over all results. Like the while loop example in http://www.php.net/manual/en/function.mysql-fetch-assoc.php

php - get how many available ads from table

I have this table advertisements, where I store all my advertisements. Everytime a user clicks on an advertisement, I record that click into a table called advertisement_clicks.
What I store in both tables is: userid and a unique token.
So, I want to count how many available advertisements there is for the user to see. Currently, I am doing it like this:
$ex = $dbh->prepare("SELECT * FROM advertisements WHERE status='2' AND fixed='0'");
$ex->execute();
foreach ($ex as $normal) {
$search2=$dbh->prepare("SELECT * FROM advertisement_clicks WHERE token=:token AND username=:username");
$search2->bindParam(":token",$normal['token']);
$search2->bindParam(":username",$userdata['id']);
$search2->execute();
}
$allnormal = $ex->rowCount();
$clickednormal = $search2->rowCount();
$normalads = $allnormal-$clickednormal;
$allnormal = how many advertisements is available.
$clickednormal = how many of these advertisements has the user clicked.
So the above approach is a bit messy and it doesn't give the correct result.
Can someone help me do this a smarter way?
You can use COUNT to get it through SQL instead.
SELECT count(*) as addCount FROM advertisement_clicks WHERE
token=:token AND username=:username"
I havn't messed with php in a while so I'm not going to even attempt to write some code lol, but the way I did it was I executed this query:
SELECT COUNT(*) FROM advertisement_clicks WHERE token=:token AND username=:username
Then get the query result which will return the advertisement count.

database trouble - same values in different rows

I am trying to make my voting system work. I have 3 databse tables:
users, posts, votes
the table users has field username as the primary key. table post has post_id as the primary key. (there are more fields but they don't affect the question/problem)
In the votes table I have 3 fields: username, post_id, vote. vote is enum ('positive', 'negative'). What I'm trying to achieve is that if a user votes for a specific post that is displayed on a page, the query: INSERT INTO votes ('username','post_id','vote') VALUES('$user_name','$post_id', 'positive'); will be executed.
It works if lets say user 123123 has not voted for any post at all yet. When this user votes lets say for post 1, this query works fine. But then if this user wants to vote for a different post, (his vote gets counted - I just copied the part of the code that doesn't work, the rest of it is fine and working) the insert query get's not executed. If user abcd wants to vote for a specific post, this works fine again, but only once. It seems to me that there is some kind of problem with the database, so that there can be only one entry with the same username or post_id. How can I fix this if I want one user to be able to vote for multiple posts? Is there a better strategy for this?
if($runloggedin->num_rows == 1)
{
// If there was no vote for the current posting, then execute this query
$query = "SELECT * FROM posts WHERE post_id='".$post_id."' AND user_name='".$user_name."'"; //get username and the post id
$result = $mysqli->query($query);
$query1 = "SELECT * FROM votes WHERE post_id='".$post_id."' AND username='".$user_name."'"; //check if there is a vote for this post already
$result1 = $mysqli->query($query1);
if ($result->num_rows == 1 && $result1->num_rows == 0)
{
$vote = "INSERT INTO votes ('username','post_id','vote') VALUES('$user_name','$post_id', 'positive')"; // this isn't working. everything else seems to be working (still test it more)
$savevote = $mysqli->query($vote);
$addvote = "UPDATE posts SET posvotes=posvotes+1 WHERE post_id='".$post_id."'";
$runvote = $mysqli->query($addvote);
echo "Thank you for your vote";
}
}
Without seeing how your votes table was created, my guess is that username has been set up as the primary key. This will make the first INSERT work, but all future ones fail. What you need to do is change it to have username & post_id be the primary key
ALTER TABLE `votes` DROP PRIMARY KEY , ADD PRIMARY KEY ( `username`, `post_id` )

How do I make sure my like button is pressed only once by user?

Like Button's table
LIKE_ID (unique like ID for each post)
LIKES (number of times someone clicks like button)
POST_ID (corresponds to the POST_ID of posts table)
A separate post table has the POST_ID from above that is unique for each post
A separate user table exists for users
So when a user clicks the like button, it adds +1 to the Like table where post_id is whatever post they are liking.
javascript file
$(document).ready(function() {
$('img.like_click').click(function() {
var form = $(this).closest('form[name=like_form]');
var lid = $(form).find('input[name=lid]').val();
$.post("like.php?lid='" + lid + "', function(data) {
$(form).find('span.like_count').html(data);
});
});
like.php file
$lid = $_GET['lid'];
mysql_query("UPDATE tbl_likes SET likes=likes+1 WHERE like_id=".$lid) or die(mysql_error());
$result = mysql_query("SELECT likes from files where fileid=" . $id) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['likes'];
I can't figure out how to stop a user from liking over and over. I found facebook style like scripts on the web that stop people from doing this, but they are based on IP address (you can't like my posts if you are not logged in) and those codes were confusing to me as I am not a jquery guy. I'm still trying to figure out how to show the like button properly using the above code, but the hardest part is restricting multiple likes which has stumped me. Anyone can help? Thanks
You said that users can't like your posts unless they are logged in. So in your case, you make it very easy for yourself. You just need to track which users liked which posts to prevent duplicates.
In the like table, remove the likes column. We'll calculate that later. Add a user_id column so you can track which users like which posts. Then add a combined primary_key on post_id AND user_id to prevent duplicates.
Then structure your query like so:
$q = mysql_query("INSERT INTO tbl_likes (user_id, post_id) VALUES ('{$user_id}', {$post_id})");
if( $q === false ) {
// query didn't work, probably a duplicate
}
else {
// return a success etc
}
And if you want to get the number of likes, use a count query like so:
SELECT post_id, count(*) as c FROM tbl_likes WHERE post_id = $post_id;

Categories