data from 2 tables

Discussion in 'PHP' started by roice, Feb 25, 2011.

  1. #1
    Hello,
    I have 2 tables:
    1.user info: user_id, name, city
    2. books info: book_id, user_id, title, category
    ( every book belong to some user - user_id)

    what will be the PHP code if I want to print all the DRAMA books from users who lives in NEW_YORK ?

    Thank you in advance.
     
    roice, Feb 25, 2011 IP
  2. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #2
    You actually need the MYSQL query , if so here it is :
    
    $result = mysql_query("SELECT * FROM books as b LEFT JOIN users as u ON b.user_id = u.user_id WHERE u.city = 'NEW_YORK' AND b.category = 'DRAMA'");
    if(mysql_num_rows($result) > 0)
    {
    while($row = mysql_fetch_array($result))
    {
    echo $row['title'].' - '.$row['category'].' - '.$row['name'].' - '.$row['city'].'<br />';
    }
    }
    
    PHP:
     
    tvoodoo, Feb 25, 2011 IP
  3. roice

    roice Peon

    Messages:
    200
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    First of all- Thanks!
    second - can you please explain to me, part by part, what you did?
    books as b LEFT JOIN users as u ON b.user_id = u.user_id WHERE u.city = 'NEW_YORK' AND b.category = 'DRAMA'
    PHP:
    what is "b" and "u"?

    does LEFT JOIN do the maching between BOOKS and USRES tables?
     
    roice, Feb 26, 2011 IP
  4. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #4
    Thats why you have google.
     
    tvoodoo, Feb 26, 2011 IP
  5. roice

    roice Peon

    Messages:
    200
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    yes, you are right, but sometimes the explaintion that you find there isn't clear enough...
     
    roice, Feb 26, 2011 IP
  6. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #6
    Its pretty clear if you search for "mysql LEFT JOIN on google" and "mysql table as"
     
    tvoodoo, Feb 26, 2011 IP