views:

22

answers:

2

Hi all,

Let me illustrate this with an example.

  1. Consider there are 10 books (there may be more, even 100+ on a single screen). A customer can order any number of books. In the fontend, each book is represented in a row and the book details are arranged column wise. Now the 10 books (along with their details) are shown in 10 rows.

    BOOK_NAME   DESCRIPTION   PRICE 
    B1          Book 1      10      Checkbox
    B2          Book 2      20      Checkbox
    B3          Book 3      30      Checkbox
    B4          Book 4      40      Checkbox
    ...
    B10           Book 10     100     Checkbox
    ------------------------------------------
    Add to Cart button
    
  2. Now, a user can check any number of books above. When 'Add to Cart' button is clicked, I would like the next screen to show the details of the selected books in the above format. So for example, if the user selects: B1, B3 and B10 and clicks 'Add to Cart' button, in the next screen, I want to show it as below:

    BOOK_NAME DESCRIPTION    PRICE  IN_STOCK
    B1          Book 1      10          2 
    B3          Book 3      30          5
    B10           Book 10     100         1
    

I have added the 'In stock' column. In this column, the number of each of the books (in stock) is shown.

I am having trouble with my current query doing the above, so would really helpful if anyone can help me with this. I have indicated the parts where I am experiencing the most trouble by placing ????? there. I am trying to do this in the most efficient way and in a single query without having to perform the query over and over (in a loop). (Please note that in case 50 books were checked, then the 50 rows of books with their relevant info needs to be shown. So hopefully that makes sense.)

My current query:

SELECT 
(SELECT COUNT(*) FROM books_stock WHERE books_stock.book_id ????? ) AS  books_in_stock,
                books.book_id, books.description, books.book_price, books.book_name
                FROM books 
                INNER JOIN books_stock  ON books.book_id = books_stock.book_id
                WHERE book_id ?????

I believe once the query is done, I would need to do a

while( $rows = mysql_fetch_array($result) )

in order to be able to show the results. Am I right?

Thank you.

A: 
SELECT 
(SELECT COUNT(*) FROM books_stock WHERE books_stock.book_id = books.book_id ) AS  books_in_stock,
            books.book_id, books.description, books.book_price, books.book_name
            FROM books 
            INNER JOIN books_stock  ON books.book_id = books_stock.book_id
            WHERE book_id IN (21, 23, 30)
Ignacio Vazquez-Abrams
Awesome! Thank you.
Devner
A: 

It was a long time since I used MySQL, but in oracle you could replace your ???? with

IN (1,2,3,4,5)

where 1,2,3,4,5 is a comma-separated list of your book ids.

I'm pretty sure that would work in MySQL as well.

wasatz
Thank you for your response. The other solution worked well.
Devner