My table is comment_likedislike. It has the comment_counterid, comment_counter, comment_id(which is from another table) fields.
And I have an url (LIKE) that when clicked would link to this code and get the comment_id and like_id.
I want to do a count where if it is the first ‘like’, it would store a new comment_counter in the comment_likedislike table. But if there is already a ‘like’ for the comment in the table, it would just update the comment_counter to +1.
Problem: When I run this code, it doesn’t UPDATE(1st statement) but INSERT(2nd if statement) no matter if there is a like for the comment or not. I don’t think the code is checking if the comment_id is in the table already.
I am a novice php programmer.
Thanks!
if (isset($_GET['comment_id']) && isset($_GET['like_id'])) {
$query5="SELECT * FROM comment_likedislike ";
$data5=mysqli_query ($dbc, $query5);
while ($row5= mysqli_fetch_array($data5)){
$comment_id2=$row5['comment_id'];
}
if ($comment_id2 == $_GET['comment_id']){
$counter=$row5['comment_counter'];
$counter++;
$query= "UPDATE comment_likedislike SET comment_counter ='$counter' WHERE comment_id= '".$_GET['comment_id']."' ";
mysqli_query($dbc, $query);
}
if ($comment_id2 != $_GET['comment_id']) {
$counter2=1;
$query9 = "INSERT INTO comment_likedislike (comment_counter, comment_id) VALUES ('$counter2', '".$_GET['comment_id']."' )";
mysqli_query($dbc, $query9);
}
}
I’m trying to infer what you’re trying to do based on your code. It looks like you’re trying to increase a counter in a row corresponding to a given comment ID present in your GET parameters. And if there is no row corresponding to that comment you want to create a new one.
If that’s what you’re intending to do then you’re going about it all wrong. It’s kind of difficult to explain how wrong your code is because I can’t figure out what mindset you’d have to be in to come up with code like that.
First of all, you should put your check for the existence of the row in the SQL query, then you need to revise the structure of your if statements:
I’d also recommend reading Best way to stop SQL Injection in PHP because you never want to be building queries the way you’re doing it in your example. (Or mine, for that matter.)