I've been trying to build a statistics page in php using a mysql db. I got most of the database running as intended but I'm running into problems on how to use php to format it in the way I want to. I have 3 tables: A, B and A_B. I want to format it as follows:
Code:
	B1	B2	B3
A1	A1_B1	A1_B2	A1_B3
A2	A2_B1	A2_B2	A2_B3
A3	A3_B1	A3_B2	A3_B3
I can't for the life of me construct an SQL query that gives me the following rows:

select A.val as '', foreach B.id (A_B.val where A_B.b_id = B.id and A_B.a_id = A.id) as B.val
from A, B, A_B
order by A.val;

Any SQL or php guru that can push me in the right direction? Also as a side question, is it possible in php to get the column name of field? Otherwise it might become a problem if I want to make the columns able to be sorted (ASC, DESC or not sorted).