Implementing A Like/dislike Counter With Php And Jquery
Solution 1:
The technical problem is this line:
$.get("./scripts/likecounter.php", {_choice : choice, _site : site, _id : id}...
as site and id are undefined you'll be getting a javascript error ReferenceError: site is not defined
Try:
$.get("./scripts/likecounter.php", {_choice : choice, _site : "<?php echo $site; ?>", _id : "<?php echo $imgid; ?>"}...
You don't need the hidden inputs, also onClick
should be onclick
.
Other quick suggestions:
Make sure $imgid is actually an integer:
$imgid = intval($_GET['_id']);
if($imgid == 0) exit('Invalid id');
The following doesn't need to be separate:
$likes = $mysqli->query("SELECT like FROM $table WHERE id = $imgid");
$dislikes = $mysqli->query("SELECT dislike FROM $table WHERE id = $imgid");
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
$mysqli->query
will only return a mysqli_result, meaning you can't just echo it out, you'll have to do a fetch, and because you know you are only getting a single result you can just use list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
Have a read of the docs to help you understand what the heck I'm going on about.
As you mentioned people can just keep hitting like/dislike all they want, you'll need to limit this with an IP log of some sort. For example setup a new database table with the following fields; ip, table, imgid. Then when someone "likes" log their IP:
$sql = "INSERT INTO xxx (ip, table_name, imgid) VALUES(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)";
$mysqli->query($sql);
Then check if they have a record before adding a new like:
$sql = "SELECT ip FROM xxx WHERE ip = \"".$_SERVER['REMOTE_ADDR']."\" AND table_name = "$table" AND imgid = $imgid";
$result = $mysqli->query($sql);
if($result->num_rows == 0) { ...if($input ==... }
Solution 2:
I think
$site = $_GET['site'];`
Should be
$site = $_GET['_site'];`
You are also not sending the id
- $imgid = $_GET['id'];
Please look into PDO or MySQLi as your code is unsafe (look up SQL injection).
Solution 3:
I believe you will need to change the column name "like" to something else as that word is reserved in SQL here is a list of reserved words
just change it to "likes" or something like that.
another minor thing is that you can get both values in a single query
Select likes,dislikes from $table where id = $ImgID
Post a Comment for "Implementing A Like/dislike Counter With Php And Jquery"