Relational database (grabbing data)

Discussion in 'PHP' started by encom, Jul 22, 2009.

  1. #1
    Hi again,
    another beginers question from me :eek:

    I have tried a few google searches and just end up in dead ends so here I go:

    I have two mysql tables.

    Table 1:
    ---------------
    game_id | title
    ---------------

    Table 2:
    ---------------------
    game_id | other stuff
    ---------------------

    How can I output the contents of table 2 but use the title from table 1 when the id's match.

    This is what I have so far:
    
    // Connect to DB
    include('../includes/dbconnect.php');
    
    $query = mysql_query("SELECT * FROM user_favourites WHERE user_id = $user_id");
    
    if(mysql_num_rows($query) == 0){
    echo 'It seems you have no favourites yet.';
    }else{
    		
    echo '<table border="1">';
    		
    //Puts it into an array 
    while($info = mysql_fetch_array( $query )) 
    {
    
    echo // title from table 1
    echo // other stuff from table 2
    
    }
    }
    
    PHP:
    Thank you.
     
    encom, Jul 22, 2009 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    You need to do a quick join to get the tables together. Assuming that this is a 1-1 relationship between the tables:

    SELECT table_1.game_id, table_1.title, table_2.other_stuff FROM table_1
    INNER JOIN table_2 ON table_1.game_id = table_2.game_id

    If you need just the result from a single game_id, use:

    SELECT table_1.game_id, table_1.title, table_2.other_stuff FROM table_1
    INNER JOIN table_2 ON table_1.game_id = table_2.game_id
    WHERE table_1.game_id = 'some_id'
     
    jestep, Jul 22, 2009 IP
  3. encom

    encom Member

    Messages:
    58
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    Complete genius,

    Worked first time with no errors :D Thank you so much.
     
    encom, Jul 22, 2009 IP
  4. ezprint2008

    ezprint2008 Well-Known Member

    Messages:
    611
    Likes Received:
    15
    Best Answers:
    2
    Trophy Points:
    140
    Digital Goods:
    1
    #4
    ukGrant.. search Google for innerjoins and leftjoins
     
    ezprint2008, Jul 22, 2009 IP