Jump to content

Selecting data from two tables


rcouser

Recommended Posts

Hello I currently have two tables as below and I want to pull the information and display like

(Location) Listing_title eg (London) Welcome to London

 

how do I get the Location_id from the Listing table to compare with the Location table and then select the Location

 

Location

Location_id

Location

 

Listing

Listing_id

Location_id

Listing_title

Listing_description

 

Thanks

Link to comment
Share on other sites

SQL for first part:

 

$sql = "SELECT Location_id FROM Location WHERE Location='London'";

$rs = mysql_query($sql); //(If you have a connection you need to have ($sql,$conn)

 

After using the mysql_query function you set the mysql_fetch_array function in a While loop.

 

While($row = mysql_fetch_array($rs))

{

  $LocationID = $row['Location_id'];

  $sql2 = "SELECT * FROM Listing WHERE Location_id ='$LocationID'";

  $rs2 = mysql_query($sql2);

  $row2 = mysql_fetch_array($rs2);

 

  $ListingID = $row2['Listing_id'];

  $ListingTitle = $row2['Listing_title'];

  $ListingDesc = $row2['Listing_Description'];

}

Link to comment
Share on other sites

$sql = "SELECT loc.Location, lis.Listing_id, lis.Listing_title, lis.Listing_description FROM Location loc JOIN Listing lis ON loc.Location_id = lis.Location_id";

 

no need to do 2 queries

 

If you want to make sure you get all the location even though there is no matching listing use LEFT JOIN rather than JOIN

 

Ray

Link to comment
Share on other sites

Thank for all the help guys, I got it working by modifying GingerRobot's post

 

SELECT listing_id, listing_title, listing_description, location

FROM listing, location

WHERE listing.location_id = location.location_id

 

Much appreciated.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.