开发者

How to check MySQL results during a 'while' table generation

Lets see if I can explain this. I am displaying a table in PHP with up/downvote arrows. PHP calls a MySQL query to get the data, then places it in a tab开发者_运维知识库le with a "while" loop. During this loop, I want to check and see if a user has already upvoted a row, and represent that with a different looking up arrow, etc. This is how I have gone about this so far.

If a user upvotes something, it is stored in a mysql db that looks something like this:

username| upvote| item_id 
Bob     | 1     | 2293
Bob     | 1     | 2295
Sally   | 1     | 2295 

How do I tell php to check if "Bob" has a "1" on item "2293" in the middle of a while loop of a different MySQL array?

echo '<table>';
while ($row = mysqli_fetch_array($data)) {
    echo '<tr>';
//insert php statement checking $row2 to see if Bob has upvoted the data in this row
//so I can place the appropriate arrow here
    echo '</tr></table>';
}


What you need here is probably a MySQL join query. An example could be:

Your existing SQL:

SELECT * FROM `items`

We then join all rows from table "upvotes", but only those rows which the current user has placed:

The final SQL:

SELECT `items`.*, COUNT(`upvotes`.`item_id`) AS `upvotes` FROM `items` LEFT JOIN (`upvotes`) ON (`upvotes`.`username` = $currentUserName AND `items`.`id` = `upvotes`.`item_id`) GROUP BY `items`.`id`

Then you should be able to use the same PHP code, but now you can check if "$row['upvotes'] > 0".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜