0

I have this code which lists everything in tbl_inventory for a given company which works fine:

$result_inventory = mysqli_query($con,"SELECT * FROM tbl_inventory WHERE company_id='$company_id' ORDER BY ip_address")

while($row = mysqli_fetch_array($result_inventory))
echo "<td>{$row['type']} </td>";
echo "<td>{$row['ip_address']} </td>";
echo "<td>{$row['site']} </td>";

The site column gives a number which correlates to an ID in another table which I want to use to run another query such as:

SELECT name FROM tbl_sites WHERE site_id='$site'

However I'm not sure on how to define $site from the previous result

Could someone point me in the right direction?

2
  • How is it correlating - one to one or many to one? Commented May 2, 2015 at 11:44
  • A perfect example where you's want to use JOIN operations (dev.mysql.com/doc/refman/5.0/en/join.html) Commented May 2, 2015 at 12:01

2 Answers 2

0

@Rayblade's answer seems legit, however, you can also perform a JOIN-statement between the two tables:

SELECT tbl_sites.name FROM tbl_inventory 
LEFT JOIN tbl_sites ON tbl_inventory.site = tbl_sites.site_id 
WHERE tbl_inventory.company_id='$company_id' 
ORDER BY tbl_inventory.ip_address

This will successfully get the tbl_sites.name column, for every company that matches a site. Here you can of course get any arbitrary number of columns, just make sure to use the table name as prefix, since we now have two tables in the query.

Sign up to request clarification or add additional context in comments.

1 Comment

This did the trick, thanks - I'm new to PHP/SQL and always wondered when I'd need to start using joins
0

You could use something like:

$result_inventory = mysqli_query($con,"SELECT * FROM tbl_inventory WHERE company_id='$company_id' ORDER BY ip_address")

while($row = mysqli_fetch_array($result_inventory)){
  echo "<td>{$row['type']} </td>";
  echo "<td>{$row['ip_address']} </td>";
  $result2 = mysqli_query($con,"SELECT name FROM tbl_sites WHERE site_id='$row[site]'")
  if ($row2 = mysqli_fetch_array($result2))
    echo "<td>{$row2['name']} </td>";
}

but i think it's a so inefficient

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.