Search code examples
phpmysqlsqlsql-like

Likes Button from phpacademy


I have been working on the header recently. Now I'm end up to create some likes button like Facebook do.

I'm following the PHPacademy on Youtube. The one who's called Alex is really awesome to share what his idea is.

The problem is, I can't show the user name and the product name which to be liked

This is my query:

function plus_the_like($meal_id) {
    $meal_id = (int)$meal_id;
    $user_name = mysql_query("SELECT `fullname` FROM `users` WHERE `user_id` = (".$_SESSION['user_id'].")");
    mysql_query("UPDATE `meal` SET `likes_meter` = `likes_meter` + 1 WHERE `meal_id` = $meal_id");
    mysql_query("INSERT INTO `likes` (`user_id`,`user_name`, `meal_id`) VALUES (".$_SESSION['user_id'].", $user_name, $meal_id)") or  die(mysql_error());
}

I know what I am doing wrong just on my query, but ahh... When I'm using the SQL in MySQL all works so well:

SELECT `fullname` FROM `users` WHERE `user_id` = 1

And that query can show me what is the username with the user_id 1 I hope that I can put that username from users table into likes table


Solution

  • Here is what you should be doing.

    You have a users table with the following information

    id - this is a unique ID of the user, this should be marked as a primary key. Auto incrementing.

    Keep whatever else information you want on the user, possibly name, email, etc.

    You have an articles table (or whatever your likes are based off of. id - this is a unique ID of the article, this should be marked as a primary key. Auto incrementing.

    Store whatever information you want on your articles, or your items in a store or whatever it is you want to "like".

    You have a likes table. id - this is a unique ID of the like, this should be marked as a primary key. Auto incrementing. user_id - this is a unique ID of your user that clicked the like button, should be marked as a foreign key. article_id - this is a unique ID of your article that was "liked", should be marked as a foreign key.

    With this, whenever a user "likes" an article, you would have a query like

    INSERT INTO likes (user_id, article_id) VALUES (:userID, :articleID);
    

    and to count the number of likes on a given article, you would do something like

    SELECT count (user_id) FROM likes WHERE article_id = :articleID;
    

    This will allow you to track how many likes for each article, as well as what each user liked. Potentially, you could eventually suggest things to users based on what they have liked. Though, that is a lot more work to do.

    This is a very basic version of what you are attempting to accomplish. As people in the comments have said, look into properly sanitizing your database input. If nothing else, at least change to my_sqli_* if you do not have PDO access. PDO is the suggested way to go though, if you are not going to use a framework that gives you all of this.