Show Name Instead of ID from Different Table

The SQL keyword you’re looking for is JOIN. Your query could be something like this:

SELECT * FROM employee INNER JOIN category ON employee.category_id = category.id WHERE id = ...

Or, more readably:

SELECT
  *
FROM
  employee
  INNER JOIN category
    ON employee.category_id = category.id
WHERE
  id = ...

(Note: I removed that last bit of the WHERE clause on purpose because I’m not comfortable putting SQL injection vulnerabilities in an answer. Please read this to learn some of the basics of properly executing SQL queries involving user input. Currently your code is wide open to a very common form of attack.)

Since some of your columns share the same name, you may even want to more explicitly request them:

SELECT
  employee.id AS employee_id,
  category.id AS category_id,
  category.name AS category_name
FROM
  employee
  INNER JOIN category
    ON employee.category_id = category.id
WHERE
  id = ...

Then in your code you’d have access to these fields:

employee_id, category_id, category_name

So you could output the value you want:

echo $website_cat['category_name'];

Leave a Comment