Monday, 30 September 2013

Using Joins to query two tables

Using Joins to query two tables

I have two tables, "inventory" and "inventory_type". The "inventory" table
stores the name of it and the type, and the "inventory_type" table stores
the type name such as RAM, CPU, etc. and the sort order. I have never used
JOINS before and I am not sure which type to use, but none of them seem to
work with the following code.
As a side question, with my code below, would "inventory" be the left
table or would "inventory_type" be joined in on the left?
function getInventoryOptions($db, $default_value, $datacenter)
{
$query = "SELECT inventory.id, inventory.name, inventory_type.short_name
FROM inventory LEFT JOIN inventory_type
ON inventory.type = inventory_type.id WHERE
inventory.datacenter = " . $datacenter . " ORDER BY
inventory_type.sort_order ASC";
$result = mysql_query($query, $db);
echo '<option value="">None</option>';
if ($result)
{
while($row = mysql_fetch_array($result))
{
$id = $row["inventory.id"];
$name = $row["inventory.name"];
$type = $row["inventory_type.short_name"];
if ($default_value == $id)
{
echo '<option selected value="' . $id . '">' . $type . ":
" . $name . '</option>';
}
else
{
echo '<option value="' . $id . '">' . $type . ": " . $name
. '</option>';
}
}
}
}

No comments:

Post a Comment