如何从另一个表中获取表的数据?

时间:2018-02-15 17:52:21

标签: php mysql

我有这两个表,table1作为类别,table2作为每个类别中的项目,现在我想要做的是得到table2的项目总数,其id等于table1。

Table1
---------
Cats id = 1
Dogs id = 2
Chickens id = 3

Table2
-------
Mouse hunt = under Cats category (table1)
Mouse hunting = under Cats category (table1)
Dog Whisperer = under Dogs category (table1)
Chicken Pasta = under Chickens category (table1)
Chicken Soup = under Chickens category (table1)
How to make chicken Broth = under Chickens category (table1)
Chicken BBQ = under Chickens category (table1)

根据表2,我在Cats类别中有2个项目,在DOgs类别上有1个项目,在鸡肉下有4个项目。

在创建这些文章/数据时,我通常会获得table1 ID并将其作为invid存储在table2上,这样我就可以轻松地获取并在其他数据中分离数据。

现在问题是我只是得到了总数:(这是我的代码

<?php
session_start();
include_once 'connect.php';

if ($_SESSION['userSession']!=1) {
 header("Location: admin.php");
}

$query = $DBcon->query("SELECT * FROM table1");
$DBcon->close();

?>

<html>
  <head>
  <title>Categories</title>

  </head>
    <body>
    <link rel = "stylesheet" href = "css/main.css">
        <div class="main-head" STYLE="FONT-size:20px;text-align: center; padding-top:20px;">
        <strong STYLE="FONT-size:28px;">Just another blog</strong>
        <BR/><a href="account.php"><img src="img/back.png"/></a>&nbsp;|&nbsp;<a href="logout.php?logout"><img src="img/logout.png"/></a>
        </div>
        <div class="main-body"> 
<h1 align="center">Categories</h1>

    <?php

while($userRow=$query->fetch_array()) {

$cid = $userRow['id'];
$subtotal = $DBcon->query("SELECT * FROM table2 WHERE invid=$cid");
$total =  mysqli_num_rows($subtotal);

echo

 '<table width="100%" border="0" style="color:#fff;border: 5px #fff solid;margin-bottom: 20px;">
  <tr>
    <td rowspan="4" align="center" valign="top">
    <img src="inventory/' . $userRow['file'] . '" width="100" height="200" /></td>
    <td align="left" valign="top">
    <a href="viewitems.php?id='. $userRow['id'] . '"><h2 style="line-height:10px;">' . $userRow['name'] . '</h2> </a>   
    <strong>Category Name:</strong> ' . $userRow['name'] . '
    <br>
    <strong>Totalitems:</strong> ' . $total  . '    
        </td>

</table>';
}
?>

        </div>
    </div>
</body>
</html>

现在我收到此错误

mysqli::query(): couldn't fetch mysqli
有人可以帮帮我吗?

谢谢

1 个答案:

答案 0 :(得分:0)

您在$DBcon->close();行上的table1查询后关闭数据库连接,稍后再尝试使用$subtotal = $DBcon->query("SELECT * FROM table2 WHERE invid=$cid");再次调用

将该行移至您使用数据库查询完成的位置,您应该没问题。

作为旁注,您可能希望使用prepared statements并使用COUNT()返回与第二个查询匹配的行数。