首页 > 解决方案 > How foreach in two table with php

问题描述

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?

标签: phpforeach

解决方案


as it combination of two tables, we cann't get level value directly. You need to get level value by another query. I hope below code will works to you.

$id = $_GET['id'];
$query = "SELECT * FROM post WHERE id='$id' "; 
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) 
{
   echo ' Name: '.$row["name"]; 
   $cats =  explode(",",$row["cat_id"]);
   $level='';
   foreach($cats as $cat) 
   {
       $lvlQry = mysqli_query($db, "Select level from cat where id=$cat");
       $lvlRes = mysqli_fetch_assoc($lvlQry);
       $level. = $lvlRes['level'];
   }
   echo ' - LEVEL:'.$level;
}

推荐阅读