I have the following tables in my database:
CREATE TABLE subjects (
subject_id int(11) NOT NULL AUTO_INCREMENT,
subject_name text,
PRIMARY KEY (subject_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE users_subjects (
users_subjects_id int(11) NOT NULL AUTO_INCREMENT,
user_id_fk int(11),
subject_id_fk int(11),
FOREIGN KEY(user_id_fk) REFERENCES users(id),
FOREIGN KEY(subject_id_fk) REFERENCES subjects(subject_id),
PRIMARY KEY (users_subjects_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
In the table 'users_subjects' I’m trying to relate the 'subjects' and 'users' tables. All the data in the tables are entered from my index.php.
I introduce the subject_name from my index.php and every time I enter a new one, checkboxes like these are created in the part where the user is added:
In this way, when entering a user and choosing the subjects that are desired, the 'users_subjects' table is created.
If for example I enter a user 'EXAMPLE' with ID = 1 and the SAT and ICT subjects with IDs 1 and 2, the 'users_subjects' table would look something like this:
The problem is that I am trying to show the users with their corresponding subjects in a PHP table but I doN’t know how to show the subjects separated by commas in the column 'SUBJECT'. I would like to do something like the following image but I don’t know how to do it. Can somebody help me? Thank you
This is my index.php:
<table class="users">
<tr>
<th colspan="2"><h2>Users registered</h2></th>
</tr>
<tr>
<th> USER </th>
<th> SUBJECT </th>
</tr>
<?php
$result = $conn->query($sql);
$sql = "SELECT * FROM users WHERE rol='profesor'";
$result = $conn->query($sql);
$sql2 = "SELECT * FROM users_subjects WHERE id=$id";
$result2 = $conn->query($sql2);
if ($result->num_rows==0){
echo 'No professors >';
}else{
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["username"]."</td>
<td>".$row["subject"]."</td>
</tr>";
}
}
?>
</table>