HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpModerate

Did you like my product?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
didproductlikeyou

Problem

I have the following MySQL query which selects product details and whether the viewing user likes them. I feel like it could be more efficient and that there is a more practical approach than using a sub-query here.

Any suggestions?

SELECT p.*, 
         pm.filename AS thumbnail,
         (SELECT COUNT(id) FROM likes WHERE productId = p.id AND 
                userId = '$viewingUserId' AND isActive = '1' LIMIT 1) 
            as liked
            FROM products p, productmedia pm
        WHERE p.userId = '$userId'
        AND p.id = pm.productId
        AND pm.sortOrder = '0'
        ORDER BY p.timestamp DESC

Solution

More important than the performance, your code is very likely vulnerable to SQL Injection. (I can't say for sure without looking at your PHP code)

If $viewingUserId or $userId is chosen by the user in any way, then you have a problem. And even if it is not, I would highly recommend using prepared queries.

I don't know if you're using the mysql_ methods or mysqli_ methods or the PDO extention, but you should be aware that the mysql_* methods are deprecated (That means: Don't use them) and that you should either use mysqli (note the i) or PDO.

Context

StackExchange Code Review Q#55211, answer score: 15

Revisions (0)

No revisions yet.