This post about Dzone like voting system with jQuery, Ajax and PHP. This script helps you to display user votes on blog post. IP address based voting system I hope you like this thanks! Take a look at live demo and give your votes.
Database Design
Messages Table :
CREATE TABLE messages(
mes_id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT,
up INT,
down INT);
mes_id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT,
up INT,
down INT);
Voting_IP Table : Storing IP address
CREATE TABLE Voting_IP(
ip_id INT PRIMARY KEY AUTO_INCREMENT,
mes_id_fk INT,
ip_add VARCHAR(40),
FOREIGN KEY(mes_id_fk)
REFERENCES messages(mes_id));
Foreign key tutorialip_id INT PRIMARY KEY AUTO_INCREMENT,
mes_id_fk INT,
ip_add VARCHAR(40),
FOREIGN KEY(mes_id_fk)
REFERENCES messages(mes_id));
Voting.php
Contains javascript, PHP and HTML code. $(".vote").click(function(){}- vote is the class name of anchor tag. Using element.attr("id") calling vote button value(messsage Id).
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
});
<script
$sql=mysqli_query($db,"SELECT * FROM messages LIMIT 9");
while($row=mysqli_fetch_array($sql,MYSQLI_ASSOC))
$mes_id=$row['mes_id'];
$up=$row['up'];
$down=$row['down'];
<div class='up'>
<a href="" class="vote" id="<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?></a></div>
<div class='down'>
<a href="" class="vote" id="<?php echo $mes_id; ?>;" name="down">
<?php echo $down; ?></a></div>
</div>
<div class='box2' ><?php echo $msg; ?></div>
</div>
<?php } ?>
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
$(this).fadeIn(200).html('<img src="dot.gif" />');$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
else
{
$(this).fadeIn(200).html('<img src="dot.gif" />');$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});});
<script
//HTML Code
<?php
include('config.php');$sql=mysqli_query($db,"SELECT * FROM messages LIMIT 9");
while($row=mysqli_fetch_array($sql,MYSQLI_ASSOC))
{
$msg=$row['msg'];$mes_id=$row['mes_id'];
$up=$row['up'];
$down=$row['down'];
?>
<div class="main">
<div class="box1"><div class='up'>
<a href="" class="vote" id="<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?></a></div>
<div class='down'>
<a href="" class="vote" id="<?php echo $mes_id; ?>;" name="down">
<?php echo $down; ?></a></div>
</div>
<div class='box2' ><?php echo $msg; ?></div>
</div>
<?php } ?>
up_vote.php
Contains PHP code.
<?php
include("config.php");$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$id=$_POST['id'];$id = mysqli_real_escape_string($db,$id);
//Verify IP address in Voting_IP table
$ip_sql=mysqli_query($db,"select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");$count=mysqli_num_rows($ip_sql);
if($count==0)
{
// Update Vote.
$sql = "update Messages set up=up+1 where mes_id='$id'";mysqli_query($db, $sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$id','$ip')";mysqli_query( $db,$sql_in);
echo "<script>alert('Thanks for the vote');</script>";
}
else{
echo "<script>alert('You have already voted');</script>";
}
$result=mysqli_query($db,"select up from Messages where mes_id='$id'");
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$up_value=$row['up'];
echo $up_value;
}
?>
down_vote.php
You have to modify up_vote.php code just replace word up to down in SQL statements.
CSS Code:
#main
{height:80px;
border:1px dashed #29ABE2;
margin-bottom:7px;
width:500px;
}
.box1
{float:left;
height:80px;
width:50px;
}
.box2
{float:left;
width:440px;
text-align:left;
margin-left:10px;
height:60px;
margin-top:10px;
font-weight:bold;
font-size:18px;
}
.up
{height:40px;
font-size:24px;
text-align:center;
background-color:#009900;
margin-bottom:2px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
.down
{height:40px;
font-size:24px;
text-align:center;
background-color:#cc0000;
margin-top:2px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
}
config.php
Database configuration file.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
More jQuery and Ajax Tutorials : Click Here
simple and cool
ReplyDeleteLittle modification added alert messages.
ReplyDeleteelse
{
echo "<script>alert('You have already voted');</script>";
}
Another vote system based on jQuery: http://www.vlkomarov.info/projects/jquery/very-simple-rating-system/ - more simple: only positive voting..
ReplyDeleteWish I could change my vote.
ReplyDeletegood
ReplyDeleteThanks
ReplyDeletenice i used it at : http://fcukmylife.us
thanks, it's very useful samples for me. :)
ReplyDeleteGreat piece of work. Thanks.
ReplyDeleteMinor changes that may be helpful:
use same case for the table names as they are created in all the files, particulary up_vote.php and down_vote.php. It seemed to create some problems for me.
very nice
ReplyDeletethanks
fghj
ReplyDeletehow can I display the items on pages in descending order of votes i.e. item with most votes get listed at top ?
ReplyDeleteHi, excellent work. I am interested into the same problem like previous user, how to get listed the items over their votes number? The one with the biggest number to be the first and so on... Thanks a lot
ReplyDelete@ken
ReplyDeleteuse ORDER BY up DESC in voting.php
example:
include('config.php');
$sql=mysql_query("SELECT * FROM messages ORDER BY up DESC LIMIT 9");
while($row=mysql_fetch_array($sql))
hey guys trying to get this right I connected to database but when I try to vote i get the following error. I am kind of a newbie
ReplyDeleteWarning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in/home/content/g/e/t/getinthegame/html/sportzline/up_vote.php on line 30
line 30 says
$result=mysql_query("select down from Messages where mes_id='$id'");
Any Help?
Hey guys, great work, I will use it in my actual onlineshop project. Thanks!!
ReplyDeleteyou can vote infinitive up votes unless you change
ReplyDelete"Messages" to "Voting_ip" in up_vote.php, compare it to down_vote.php and see the diffrence
Same probleme
ReplyDeletehey guys trying to get this right I connected to database but when I try to vote i get the following error. I am kind of a newbie
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in/home/content/g/e/t/getinthegame/html/sportzline/up_vote.php on line 30
line 30 says
$result=mysql_query("select down from Messages where mes_id='$id'");
Any Help?
its amazing...you are great dude
ReplyDeletei get the same error...
ReplyDeleteWarning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /homepages/8/d217407391/htdocs/webgroup/donlope/voting/up_vote.php on line 30
What can we do???
Adrian said...
ReplyDeletecos $sql - are not returned a result.check your query.
"are not returned a result.check your query..."
ReplyDeleteI dont understand..
i have been trying to make this code work on my site for one whole week and not been able to start it. All it shows its the title of the script and rest everything else is missing. Yes i checked the config file and have put in correct entries. Can anyone help me with this?
ReplyDeleteHow could you turn the votes into a percentage?
ReplyDeleteExample:
Do you like this?
Yes: 80% No: 20%
Has anybody modified this so that if you click a thumbs up img the value next to it will go up e.g. youtube thumbs up thumbs down feature
ReplyDeleteHow come everything disappears when I added the jquery script?
ReplyDeletein your tutorial dont forget to fix a small mistake
ReplyDelete<*script
How can I modify the script so that the guest/visitors can also add entries to the list ?
ReplyDeletethe guest entries should first go to a backed moderation section before appearing on the site
thanks alot
ReplyDeletehow could this be implementd in wordpress? for one category? it's really good
ReplyDeleteWill try it...
ReplyDeletehello. how protect files included in ajax, like up_vote.php from run outside the script?
ReplyDeleteThank you Tamada for sharing with us, it's very usefull and looks so good.
ReplyDeleteI find the error that can get some problems, on line 32 replace M letter, with m, from table messages, and will work. $result=mysql_query("select up from Messages where mes_id='$id'");
Oh man first thank for the great work but i dont understand why you take long time and dont answer the commets. I have added the script but not working. Regards!
ReplyDeleteI need the values in the database.... please can anyone share the tables data... i created the messages table, but its empty...
ReplyDeletehow does one add messages to the database?
ReplyDeletegreat job very flexible and practical script. I vote up!
ReplyDeletevery good, its a very nice feature for site.
ReplyDeletei added a link from my ajax examples web site
www.ajaxshake.com
i get:
ReplyDeleteWarning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in .../down_vote.php on line 31
whats wrong? thx
Hi,
ReplyDeletei change your nice code for admin or auther ( blog poster) now when click for vote admin if in page LIMIT = 9 show 9 alert box ( 'You have already voted'), how to fix this?
Thanks
Srinivas Tamada !
ReplyDeletei change your nice code for admin or auther ( blog poster) now when click for vote admin if in page LIMIT = 9 show 9 alert box ( 'You have already voted'), how to fix this?
Can you help me >
wow...this is amazing...thanks for sharing this....thanks...
ReplyDeleteI just try to use your voting (and is great) but when you put it on mod_rewrite website... doesn't work. I have no ideea why. I taste the same page with or without mod_rewrite activated. When was without the script was working great, when mod_rewrite was activated... no. So, i someone have anyideea why...pls tell me :)
ReplyDeleteYes, I cam getting the same problem with mod_rewrite. Script works flawless with a query string, .e.g. yourdomain.com/index.php?sort=new&time=day, but if you have mod_rewrite to use "pretty" urls, like yourdomain.com/new/day it stops working. Anyone know the cause?
ReplyDeleteTry capitalizing Messages in DB
ReplyDeleteExcellent script and very easy ro implement thanks !!! >.<
ReplyDeletei had a problem
ReplyDeleteafter all database connected
i have voting.php page showing only
Voting with jQuery, Ajax and PHP
nice, how you added voting.php to your blog, since it is blogger hosting know, can you give a reply
ReplyDeletesame problem
ReplyDeleteWarning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/content/19/6549019/html/bb/poll/up_vote.php on line 30
Please check the SQL query
ReplyDeleteThank you for sharing this information with us.
ReplyDeleteWhat database to use?
ReplyDeleteUseful tutorial. But I saw the voting with social networks. I mean user came to the site with voting and there are several items on which he can vote with his Facebook and Twitter accounts. How can be the similar thing done with the code in this article?
ReplyDeletehi
ReplyDeletefirst of all thanks for a grate tut... but it has error... in my side and i seen more than 5-6 comment with same error
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/kiransteel.com/voting/down_vote.php on line 12
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/kiransteel.com/voting/down_vote.php on line 31
and please do not use " Message " The capital m M" it will create when it is on server side...
thanks and wait for your solution ...
Really like your blog ,because are very interesting articles here ,thanks for that.
ReplyDelete@Jocurl: mod_rewrite fix (well works for me)
ReplyDeletefull path in ajax:
url: "http://somedomain.com/up_vote.php",
great script! i change your nice code for admin on my wordpress.
ReplyDeleteThank you for the great tutorial!
ReplyDeleteI have some questions:
- Rather than clicking on the number, how to click on an image to vote?
- Is there a way to show the net vote, meaning:
net vote= positive votes-negative votes
- Is there a way to sort table by net vote, after the user clicks on up or down?
Thanks,
He still doesn't fix his problem yet, isn't it?
ReplyDeleteWarning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/kiransteel.com/voting/down_vote.php on line 12
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/kiransteel.com/voting/down_vote.php on line 31
.....
Hey, I am developing an election voting system votes of candidates goes to db mysql and should show a graph.please help..thnx and more power..
ReplyDeleteThis blog is very interesting for me and others ,I will return very soon for other items,thank you very much.
ReplyDelete..and thanks for script :)
Thanks for the script is great.
ReplyDeleteBut how can I not to vote several times those with dynamic ip.
meaning they can only vote once a day?
Thanks.
2 marian
ReplyDeleteI changed the IP to user ID (from the Users table)
So yes they go.
ReplyDeletebut only those registered voted.
I need to vote and visitors.
Great script - thanks for this (although there are one or two syntax that needed to be resolved, as mentioned in previous comments).
ReplyDeleteFor the guys having problems using it with mod_rewrite, I had the same problem but managed to resolve by changing the js in the header to:
url: "/up_vote.php",
The forward slash ensures it can find the up_vote script when using slashes in the urls (presuming up_vote,php is in the root).
Brother, i want to separate time for each vote of each user. eg. time separate 4 hour for each user vote time. how to do it. please description to me.
ReplyDeleteERROR in up_vote.php
ReplyDeleteline:
$sql_in = "insert into messages (mes_id_fk,ip_add) values ('$id','$ip')";
should be:
$sql_in = "insert into voting_ip (mes_id_fk,ip_add) values ('$id','$ip')";
You're right!
DeleteThis blog is very interesting for me and others ,I will return very soon for other items,thank you very much.
ReplyDelete..and thanks for script :)
Maybe a stupid questiong.. how does the config.php look like? what is the host, username and passwd syntax
ReplyDeleteYou add a type of score, 1+ o 1- , because spammers o kakers attack about this ¬¬..
ReplyDelete$score = (int) $_POST["score"];
if($score > 1) die("No more 1 Vote");
it's a nice script, just in file download there on bugs about the name of the table on:up_vote.php
ReplyDelete$sql_in = "insert into Messages (mes_id_fk,ip_add) values ('$id','$ip')";
There is an error:
ReplyDelete'Messages' should be replaced by 'messages' Otherwise it does not work properly
Thanks for the tutorial, i have it working, if someone has any queries, contact me clicking on my name
Works great, had to change some things to fit my sites database; but honestly one of the best scripts I've used... efficient and easy to edit!
ReplyDeleteThank you!
thnx for tutorial.it help in my project.thnx
ReplyDeleteHi,
ReplyDeleteNice ... Have u noticed that the vote is not updated after you hit refresh . Eventhough you have added "cache:false" in your ajax script , caching takes place.Please resolve the issue.
Thanks!
ReplyDeleteThanks, It's easy and useful.
ReplyDeleteI like this script. Please add one more box showing rank.
ReplyDeleteTested a script on denwer does not work. On a hosting has established, css-styles are displayed only. The script in an initial code is displayed, but does not work. In what maybe a problem prompt please?
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteI would like to have it as a plugin for my WordPress blog..
ReplyDeletecan anyone convert it to a WordPress plugin?
Thanks a lot. I will try it.
ReplyDeletethis is very cool, i just've adecuate to my especifications.. thanks a lot
ReplyDeleteHow to get the local ip address when the systems are in LAN or intranet.
ReplyDeletenice and esay code thanks
ReplyDeleteit is quiet good code but one thing strikes me is that when i click down vote ,,i get down votes suppose i want to give upvote after sometimes! that is not seem possible because you have already voted,,sometimes a user can like to vote again if he feels upvote! can you catch my point as FB has LIKE and Dislike with same button!
ReplyDeleteGreat script! thanks for this.
ReplyDeleteQuick question, if i want to show the score instead ($up - $down) how can i do that?
Thanks!
I have connected to the DB but I only get the header and nothing else on the screen
ReplyDeleteI have connected to the DB but I only get the header and nothing else on the screen
ReplyDeleteI learned lot from your blog. But I think it's time for you to update your codes using mysqli_* since they will remove the mysql_* soon. If you do update your codes lot of new visitors can benefit from that. Anyway thank you for the greate job you do
ReplyDelete$ip=$_SERVER['REMOTE_ADDR'];
ReplyDeleteIn up_vote.php, the above code is calling the ip address.
If i want to call my UserID? What code should i write :( ? Pls help Thanks
i too am getting nothing but the header as well...
ReplyDeleteI got it to work now how can i have more than one on the same page??!?1
ReplyDeleteThanx
ReplyDeletethis is hard for me to understand :P ! i talk about the script .
ReplyDeletethank you
ReplyDeleteDoes this script can be applied in rating images (individually)?. Thank you.
ReplyDeletethnq u for sharing this post
ReplyDeletethe voting for some reason doesnt workk on me...
ReplyDeleteNice script. Thank you.
ReplyDeleteDoes it work with MAMP? Everything works good but i see no numbers of voting. I have indexed mes_id_fk and related with mes_id in messages. I think i have to change mes_id in msg_id in all the voting scripts, because i have some other script.
The script is quite good, but there is a problem with php files up_vote.php and down_up.php on line number 6,stating undefined index 'id'. The tutorial is great,but I would really be obliged,if you help me in tackling why this problem is occurring,since I want to use voteup and votedown button in my project.Please help me!
ReplyDeleteThe tutorial is really great,I downloaded and made database connection the way u've mentioned ,but there is an error with the php files up_vote.php and down_vote.php on line number 6, stating undefined index id,and I'm unable to understand its occurrence,since I'm a newbie,I want to make use of vote up and vote down buttons in my project,PLZ HELP ME SOLVE THIS ERROR!!
ReplyDeletethe number of votes is not getting incremented after clicking on the button...!!!
ReplyDeleteMuchas gracias :)
ReplyDeleteAwesome work !!! Thanks :) Just what I was looking for.
ReplyDelete@Rakhi Dhavale if the numbers are not incrementing maybe is because the query that increments the value of the up and down is not working properly.
Try sending it directly through the mysql console replacing the '$id' value with a number (2 for example) and check using phpmyadmin if the value incremented. I am refering to this query "update Messages set up=up+1 where mes_id='$id" inside the up_vote.php file.
Hope it helps.
Can someone help me with this please ......
ReplyDeleteWarning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home/mmaigbo/public_html/vote/up_vote.php on line 12
down_vote.php at lint 19 and 20
ReplyDelete$sql_in = "insert into voting_ip (mes_id_fk,ip_add) values ('$id','$ip')";
mysql_query( $sql_in);
up_vote.php at lint 19 and 20
$sql_in = "insert into messages (mes_id_fk,ip_add) values ('$id','$ip')";
mysql_query( $sql_in);
is this correct.... have already solve some couple of problems but now votes are not updating
Thanks for this code, it's very helpful.
ReplyDeleteCOOL I like it
ReplyDeleteIt shows error
ReplyDeleteDeprecated: mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead. in up_vote.php on line 9
It's very helpful. Thanks a lot!
ReplyDeleteThank you I need your script :)
ReplyDeleteI was looking for this script. Thanks :)
ReplyDeletebut when my friend under similar network (same IP Address), he can't do vote. Any solution for this condition?
ReplyDeleteNotice: Undefined index: id in C:\wamp\www\voting\voting\down_vote.php on line 6
ReplyDeletehow to solve it?
Who can add the code for PHP 7, mysqli ?
ReplyDeleteUpdated.
DeleteERROR in up_vote.php
ReplyDeleteline:
$sql_in = "insert into messages (mes_id_fk,ip_add) values ('$id','$ip')";
should be:
$sql_in = "insert into voting_ip (mes_id_fk,ip_add) values ('$id','$ip')";
Warning: mysqli_connect(): (28000/1045): Access denied for user 'targetla_kjuser'@'localhost' (using password: YES) in /home/panekham/public_html/kuanjailao.com/config.php on line 6
ReplyDeleteWarning: mysql_query(): Access denied for user 'root'@'localhost' (using password: NO) in /home/panekham/public_html/kuanjailao.com/voting.php on line 152
Warning: mysql_query(): A link to the server could not be established in /home/panekham/public_html/kuanjailao.com/voting.php on line 152
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/panekham/public_html/kuanjailao.com/voting.php on line 153
I loved the way you explained the stuff.
ReplyDeleteMany thanks to almost every other excellent post.
ReplyDelete