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` )
Related
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
I have two tables:
users - Where gender information is stored:
id
username
gender
user_thoughts- Where all posts are stored:
id
added_by
What I am trying to do is determine how many posts have been made by male and female users separately. But I am just completely stumped on how to achieve this. So far, I have the following:
<?php
include ("connect.php");
// updating table posts_by_gender whenever admin logs in.
// 1.Get gender of user to compare against the author or the thought
$get_all_users_gen = mysqli_query ($connect, "SELECT gender FROM users WHERE account_type = 'user'");
while ($getting_gen = mysqli_fetch_assoc ($get_all_users_gen)){
$gender = $getting_gen['gender'];
// 2. Get all posts
$getting_thoughts = mysqli_query ($connect, "SELECT username FROM user_thoughts");
$getting_th = mysqli_fetch_assoc ($getting_thoughts);
$added_by = $getting_th['added_by'];
} // while closed
?>
I am just completely confused on what to write after this.
Summary:
Trying to check each row in user_thoughts table, get the added_by data (which is the same as username from users table) and see if that user is male or female.
At the end of the check, I need a variable which holds a number of how many posts belong to male users, and how many to female.
You can do this with a Join... An example given below
SELECT * FROM `user_thoughts` LEFT JOIN users ON user_thoughts.added_by = users.username WHERE users.gender= "male"
This will get all user thoughts by male... Then you can do a mysqli_num_rows($query) to get the count.
You can do the same for females...
However, if you only need the count, it may be adviseable to run
SELECT COUNT(*) AS number FROM `user_thoughts` LEFT JOIN users ON user_thoughts.added_by = users.username WHERE users.gender= "male"
and this would return the number of rows directly.
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
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;
I am using PHP/MYSQL. I want in my frontend, for the users to sort and rearrange database records entered by the user himself in an earlier stage. The records uploaded by the user may sometimes inserted into the database randomly, so in the user profile he/she might have a facility to rearrange the the rows in the database according to there wise.
Can any one provide me a script that would help me to do so.
id title date desc
1 s1 s1_date s1_desc
2 s2 s2_date s2_desc
3 s3 s3_date s3_desc
4 s4 s4_date s4_desc
5 s5 s5_date s5_desc
In the user profile he want to rearrange the rows so that s2 will go one up and will save as s2->s1 and s1->s2 for every field.. may be swapping of records in between
I am looking it in another way.. user page will show the field in rows wise and in the side there will be an input box of each the current row id say (id) is set as value of that input box so that the user can change in between and submit the whole reordered list to the back-end. In that case what can we do... there will be many swapings to to concurrently..
Best solution is to add another field "ordering" where you can store by default int ID, and while rearranging rows, you could swap values of ordering between these rows. In query you would do ORDER BY ordering ASC/DESC
Get both rows and update back the values:
Assuming the tablename is: t
$result = mysql_query("SELECT title, `date`, `desc` FROM t WHERE id = 1");
$row1 = mysql_fetch_assoc($result);
$result = mysql_query("SELECT title, `date`, `desc` FROM t WHERE id = 2");
$row2 = mysql_fetch_assoc($result);
mysql_query("UPDATE t SET title = '{$row2['title']}', `date` = '{$row2['date']}', `desc` = '{$row2['desc']}' WHERE id = 1");
mysql_query("UPDATE t SET title = '{$row1['title']}', `date` = '{$row1['date']}', `desc` = '{$row1['desc']}' WHERE id = 2");