Steven Steven - 7 months ago 9
PHP Question

How to modify rows in tables in HTML language

I have this code

<html>
<head>
<title> trans </title>
<body>
<style>
table, th, td {
border: 1px solid black;
width: 900px;
margin: auto;
}
h3{
text-align: center;
margin-top: 20px;
}
</style>
<?php

$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con,"uoh");
$q = " SELECT * FROM `degree_plan` LEFT JOIN courses ON
degree_plan.course_number=courses.course_number
where major='COE'";

$result = mysqli_query($con , $q) ;
if($result){
echo "<br />";
echo "<table>";
echo "<tr>";
echo "<th>courses</th>";
echo "<th>term_no</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{

echo "<tr>";
echo "<td>" . $row["code"]. "</td>";
echo "<td>" . $row["term_no"]. "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>


the output of this code like this .
Here every course in one row but I do not want like that.

--------------------------
course term_no
--------------------------
CHEM 101 1
-------------------------
ENGL 101 1
-------------------------
MATH 101 2
--------------------------
PE 101 2


how I can make the code do not separate courses that have the same term_no.
I want the the output like this

--------------------------
course term_no
--------------------------
CHEM 101 1
ENGL 101
-------------------------
MATH 101 2
PE 101

Answer

You can do an array of String where each cell of it holds all the courses in the same term_no that matches the cell id.

Try this out insead of your current while loop:

$str = array();
while($row = mysqli_fetch_array($result))
{
    $str[$row['term_no']] += ",".$row['code'];
}
foreach ($str as $key => $value)
{

   echo "<tr>";
   echo "<td>" . $value. "</td>";
   echo "<td>" . $key. "</td>";
   echo "</tr>";
}

EDIT: I changed the code abit try it now.