【问题标题】:PHP select query print out numerous items from database [closed]PHP选择查询从数据库中打印出许多项目[关闭]
【发布时间】:2021-04-07 19:37:22
【问题描述】:

My Table

所以我希望它像这样打印出来

Coffee Name:
ColumbianPrice: 7.99
Total Sold: 3
Total earnings: 23.9

然后对每种类型的咖啡重复

是否有任何网页允许我这样做

$a_result = mysqli_query($connection_var, "SELECT COF_NAME, PRICE FROM coffees");
while ($rows = mysqli_fetch_array($a_result)){
    print("<p>");
    print($rows[0]);
        print("<p>");

    print($rows[1]);
        print("<p>");

    print($rows[2]);
        print("<p>");

    print($rows[3]);
        print("<p>");

    print($rows[4]);
    print("</p>");
}

目前,这是我所拥有的,但知道它不正确。任何帮助非常感谢?

【问题讨论】:

  • 好吧,你打开了 5 个 p 元素,但只关闭了 1 个元素,这样会产生一些奇怪的格式。您也只选择 2 列,但尝试访问 5 个索引,这是另一个问题。请澄清it is not correct,值,显示,其他?

标签: php sql database


【解决方案1】:

您可能需要先更新 SQL 查询,以便以您想要的方式检索数据。

假设您的数据库表如下所示

Table: coffees

id    coffee_name    columbia_price   total_sold    total_earnings
-------------------------------------------------------------------
1     Raw Coffee     7.99             3             23.9

您的 SQL 查询应该是:

SELECT
`id` as `id`
`coffee_name` as 'Coffee Name:',
`coffee_price` as 'Columbia Price:',
`total_sold` as 'Total Sold:',
`total_earnings` as 'Total Earnings:',
from `coffees`;

这个查询的预期输出应该是

[
    [
        "id" => 1,
        "Coffee Name:" => 'Raw Coffee',
        "Columbia Price:" => '7.99',
        "Total Sold:" => '3',
        "Total Earnings:" => '23.9'
    ]
]

如果你得到了预期的结果,那么 PHP 实现应该是:

while($row = mysqli_fetch_assoc($result)) {
    foreach ($row as $key => $value) {
        echo "<p>". $key ." ". $value ."</p>";
    }
}

【讨论】:

    【解决方案2】:

    您应该调整查询以选择所有列 SELECT * FROM coffees 并将 while 循环内的内容替换为以下内容:

    while ($rows = mysqli_fetch_array($a_result)){
        echo '<p>Coffee Name: ' . $rows[0] . '</p>';
        echo '<p>Coffee Price: ' . $rows[2] . '</p>';
        echo '<p>Total Sold: ' . $rows[3] . '</p>';
        echo '<p>Total Earnings: ' . $rows[4] . '</p>';
      }
    

    这应该适用于您的桌子。

    【讨论】:

      【解决方案3】:
      $a_result = mysqli_query($connection_var, "SELECT COF_NAME, PRICE, SALES, TOTAL FROM coffees");
      
      while ($rows = mysqli_fetch_array($a_result)){
          print("<p>");
          print("Coffee Name: $rows[0]<br>
              Price: $rows[1]<br>
              Total Sold: $rows[2]<br>
              Total Earnings: $rows[3]<br>");
      }
          print("<p>");
      

      基本上是答案

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-04
        • 1970-01-01
        • 1970-01-01
        • 2012-09-01
        • 1970-01-01
        相关资源
        最近更新 更多