Jordy Jordy - 1 year ago 62
MySQL Question

How to use MySQL value ins second query?

How can I do this:

SELECT Board_id FROM topic WHERE Value1='".$value2."' UNION SELECT Name FROM Boards WHERE Id=Board_id

Should I use
? Or should I use two different queries? What is better?

Answer Source

Use a join:

select name, board_id from boards b inner join topic t on
where t.value1='VALUE1'

See a SQL join tutorial on W3 Schools:

Note, if you're using PHP, your code is at risk of SQL injection:

There are a number of ways to protect against this:

$sql = "SELECT board_id, name from boards b inner join topic t on " .
   " " .
   " where t.value1='" . mysql_real_escape_string($value2) . "'";

Better yet might be to use a parameterized query, but this depends on whether you're using PHP's MySQL or MySQLi libraries.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download