It is Table from Phpmyadmin.
Table: post
----------------------------------------
| id | cat_id | name |
----------------------------------------
| 1 | 3 | Alex |
| 2 | 1,2 | Mona |
| 3 | 1,2,3 | Sarah |
----------------------------------------
Table: cat
-----------------------
| id | level |
-----------------------
| 1 | PHP |
| 2 | #C |
| 3 | JAVA |
-----------------------
Out: (localhost/post.php?id=3)
----------------------------------------
| id | name | level |
----------------------------------------
| 3 | Sarah | PHP,#C ,JAVA |
----------------------------------------
Name: Sarah - LEVEL: PHP,#C,Java
I adopted code given in this example:
how do i remove a comma off the end of a string? and How to use implode function in foreach loop
I changed the code with the link above and it is as follows: (foreach)
$id = $_GET['id'];
$query = "SELECT * FROM post WHERE id='$id' ";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)) {
echo ' Name: '; echo $row["name"];
echo ' - LEVEL:';
$cats = $row["cat_id"];
foreach($cats as $cat) {
echo $row["level"];
}
}
Hence when I go to: http://localhost/post.php?id=3, It gives error:
Name: alex
LEVEL:
Warning: Invalid argument supplied for foreach() in C:\xampp\... "foreach($cats as $cat){"
What could be the reason and what am I doing wrong?