php - 显示来自 DB php/MySQL 的项目数组

标签 php mysql

我不确定如何显示 items 字段。我想显示两个数据表;一个包含来自用户的所有项目,一个包含所有项目给用户。我所能输出的只是 item_id 的(我在下面粘贴了 html)。如何从 item 表中的这些 id 获取所有项目信息,并填充 HTML?

转表

TRANS TABLES

项目

enter image description here

$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);

$sql->execute();

while($row = $sql->fetch())
{
    $t =$row['items'];
    $u =$row['to_id'];
    $trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$t</td>
            <td>$u</td></tr>";
} 

HTML 显示

enter image description here

最佳答案

试试这个!

<?php
    $from = 1;
   $sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
   $sql->bindValue(':id', $from);

   $sql->execute();

  while($row = $sql->fetch())
    {
     $t =$row['items'];
     $u =$row['to_id'];
             $itemIDs = @explode(",", $t);
         $items = array();
            foreach($itemIDs as $ID){
            $sqlItem = $db->prepare("SELECT itemname FROM itemtable WHERE itemid = :itemid");
            $sqlItem->bindValue(':itemid', $ID);
            $sqlItem->execute();
            $itemname ='';
            while($rowItems = $sqlItem->fetch())
            {
                $itemname .=$rowItems['itemname'];
            }

            $items[$t] = $itemname;

     }   

        $trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$t]</td>  <td>$u</td></tr>";
   }  

下面是我的测试代码,

<?php

  $from = 1;
 $sql = mysqli_query($db,"SELECT * FROM test WHERE from_id = '$from'");  
 while($row = mysqli_fetch_array($sql))
 {

     $t =$row['items'];
     $u =$row['to_id'];
     $itemIDs = @explode(",", $t);
     $itemname ='';
        foreach($itemIDs as $ID){
            $sqlItem = mysqli_query($db, "SELECT itemname FROM itemtable WHERE item_id = '$ID'");           

            while($rowItems = mysqli_fetch_array($sqlItem))
            {
                 $itemname .= $rowItems['itemname'].', ';
            }       


            $items[$u] = $itemname;

     }      
    $trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$u]</td>  <td>$u</td></tr>";
  } 

  echo "<table>".$trans."</table>";
?>

关于php - 显示来自 DB php/MySQL 的项目数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19674804/

相关文章:

php - 如何在 preg_match 中允许 utf-8 字符集?

php - Yii2 ajax 错误请求 (#400)

PHP - Codeigniter 在插入数据库时​​删除破折号和括号

mysql - MS Access 查询计算字段

php - MySQL 将哈希密码视为变量的部分

php - Laravel 收银员它不会自动创建订阅

mysql - 有没有办法在 mysql 中获得 utf8 区分大小写的排序规则?

mysql - 为什么 MySQL (MariaDB) 使用以下查询计算记录数超过 3 分钟?

sql - 选择具有相同值但有一个异常(exception)的组

PHP 无法从 mysql 查询获取列名