简体   繁体   中英

Use MySQL result in another query

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?

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

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM