Postgresql SELECT without hardcoding item

138 Views Asked by At

I have a simple PostgreSql query that looks like:

$params = array();

if ($audienceId === x) {
  // all teachers
  $pullRecipients = $db -> prepare(
    "SELECT email FROM app.employees WHERE emp_cat_id = 1 AND active is true");
}

$pullRecipients -> execute($params);

I'm running the queries based on a drop down select, so that if for example the user selects TEACHERS, the above query is run. How can I select for instance the emp_cat_id or even the category name TEACHERS without hard coding them in the query?

1

There are 1 best solutions below

0
On

change statement to something like

SELECT email
FROM app.employees
WHERE emp_cat_id = ? AND active IS true

and make sure your $params is equal to something like array($POST["drop-down_value])

and if you want to allow text value - use join, something like:

SELECT email
FROM app.employees
WHERE emp_cat_id = (SELECT id FROM emp_cat WHERE name = ?)
  AND active IS true