Update Voting System3:53 with Alena Holligan
Let’s make some updates to our voting system to make sure a user can have only a single vote registered per book. We are going to update our book list as well to show the way the user voted by changing the arrow color.
Other samples for score
echo $book['score']; ?: echo '0';
PHP 7: null coalesce operator
echo $book['score'] :: echo '0';
Breaking Down the Query
Let's break down this query now that it has become more complex.
First we select all columns from the books table and get the sum total of votes for a book and saving that column as
SELECT books.*, sum(votes.value) as score, "
The main table used in the select.
. " FROM books "
To get the score used in the select, we do a LEFT JOIN of the votes table where the id of the current book equals the book_id's from the votes table.
. " LEFT JOIN votes ON (books.id = votes.book_id) "
Then, we group everything by the book id so there is only 1 row per book
. " GROUP BY books.id "
Finally we order the books by the score DESC so the highest voted book is at the top and the lowest scored book is at the bottom.
. " ORDER BY score DESC";
You need to sign up for Treehouse in order to download course files.Sign up