从行到列

I have no problem to generate the output, But, I have no idea to to generate from rows to columns.

Simple code and output I put here.

Thanks.

$con = mysql_connect('localhost', 'root', 'xxx') 
if (!$con)   {  die('Could not connect: ' . mysql_error())   }   
mysql_select_db("kasy", $con) 
$sql="SELECT * from exam where intake='$b'"


echo "<table border='1'>
<th>name</th>
<th>subject</th>
<th>grade</th>
</tr>";

 $row= mysql_query($sql)
    {
     echo "<td>" . $row['name'] . "</td>";
     echo "<td>" . $row['subject'] . "</td>";
     echo "<td>" . $row['grade'] . "</td>";
    }

Output :

Name  | Subject  | Grade
Jose  | History  | A
Jose  | Language | A
Jose  | Account  | B
Brian | History  | B
Sarah | Math     | C

but I want something like this and I have no idea,

|Name  | History | Language | Account | Math |
|Jose  |   A     |    A     |  B      | NULL |
|Brian |   B     |  NULL    |  NULL   | NULL |
|Sarah |  NULL   |  NULL    |  NULL   |  C   |

intake='$b' = from form, I post the data.

I just want to know how to array and generate like this. Special Thanks.

You need to pivot the data. You can do this with aggregatino:

select name,
       max(case when subject = 'History' then grade end) as History,
       max(case when subject = 'Language' then grade end) as Language,
       max(case when subject = 'Account' then grade end) as Account,
       max(case when subject = 'Math' then grade end) as Math
from exam
group by name;

I don't know what the where intake='$b' is for, because you don't have an intake column in the data. Also, the mysql_ interface is deprecated, so you should use something more modern -- and with parameters to prevent SQL injection attacks.

You should be using mysqli or even better PDO as mysql has been deprecated, but try this

$con = mysql_connect('localhost', 'root', 'xxx') 
if (!$con)   {  die('Could not connect: ' . mysql_error())   }   
mysql_select_db("kasy", $con) 

    echo"<table border='1'>
        <tr>
            <td>Name</td>
            <td>History</td>
            <td>Language</td>
            <td>Account</td>
            <td>Math</td>
        </tr>";

    $result = mysql_query(SELECT * from exam where intake='$b'");

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
        {

            echo"

        <tr>
            <td>".$row['Name']."</td>
            <td>".$row['History']."</td>
            <td>".$row['Language']."</td>
            <td>".$row['Account']."</td>
            <td>".$row['Math']."</td>
        </tr>


            ";

        }