php - 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?
解决方案
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;
}
推荐阅读
- vb.net - 按钮和错误
- c# - 为什么我的 UI Button 在未单击时显示按钮单击消息?
- python - 在 pandas 数据帧上进行 Groupby,并根据列中值的频率用逗号连接字符串
- java - 线程内的 Spring @Transactional 支持
- excel - 保持执行VBA Excel的流程
- xml - 浏览 XmlNodeList (vb.net) 中的节点
- android - 如何从 webview 获取会话用户 ID
- node.js - socket.io 中默认的 pingTimeout 和 pingInterval 是什么
- c - 第二次输入后清洗管道
- vba - 添加表单控件时,全局变量莫名其妙地重置