Jordy Jordy - 11 days ago 6
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
UNION
? Or should I use two different queries? What is better?

Answer

Use a join:

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

See a SQL join tutorial on W3 Schools: http://www.w3schools.com/sql/sql_join.asp

Note, if you're using PHP, your code is at risk of SQL injection: http://en.wikipedia.org/wiki/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 " .
   " t.board_id=b.id " .
   " 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.

Comments