Hmmm, I think you have some design problems. The question ID should describe the question and this value could be passed in the link, similarly to how you did with the dept-value ( it's a quite freaky thing to call 'q' something that describes 'dept', you can loose control very easy )
When you pass the ID to request a question the SQL-queries became more simple. One for getting the question text according to ID (you won't even need a loop) and an another for getting the answers for the question.
Edit:
I think the problem is with the second query and where it's used. The result of first query contains all questions in dept.
The second query's result contains all of the answers for these questions.
I think, that the second query should be executed within the first loop:
$sql="SELECT question,q_id FROM question WHERE dept='".$q."'";
$result= mysql_query($sql);
while($row = mysql_fetch_array($result) )
{
echo "<br>";
echo "Q. ";
echo $row[0];
$q_id=$row[1];
$sql1="SELECT answer FROM answer WHERE q_id='".$q_id."'" ;
$result1= mysql_query($sql1);
while($row1 = mysql_fetch_row($result1))
{
echo "<br>";
echo "Ans. ";
echo $row1[0];
}
}
Another way could be using a join in the queries,so you can get all question-answer pairs as a result, but you must achieve, that each question should be displayed only once. So it's more simply to run multiple sql-queries.