【问题标题】:Using PHP to echo specific data from MySQL rows?使用 PHP 从 MySQL 行中回显特定数据?
【发布时间】:2020-02-17 11:38:34
【问题描述】:

这是我的 MySQL 表的示例:

id, type, value
1, total_clicks, 15
2, total_revenue, 32.42
3, conversion_rate, 1.432

我正在使用这个命令来获取所有这些行:

SELECT * FROM statistics

如何使用 PHP 根据 type 列中的内容回显 value 列?

例如,我将如何做这样的事情:

echo "We found that $total_clicks generated $total_revenue in revenue.";

通常我会将它们中的每一个都作为一列并使用fetch_assoc 来回显每一列的值,但由于某种原因决定将这些数据分成几行...

【问题讨论】:

  • 查询的输出中是否有多组数据(即typetotal_clicks的多于1行)?
  • 不,type 字段是唯一的。
  • 这被分成行的原因是你通常如何表达关系数据,因为它是一个常见的normal form

标签: php mysql sql


【解决方案1】:

您有几个选项可以存储查询结果,然后在 PHP 中输​​出:

  1. 关联数组
    while ($row = $result->fetch_assoc()) {
        $data[$row['type']] = $row['value'];
    }
    echo "We found that {$data['total_clicks']} generated {$data['total_revenue']} in revenue.";
  1. variable variables
    while ($row = $result->fetch_assoc()) {
        ${$row['type']} = $row['value'];
    }
    echo "We found that $total_clicks generated $total_revenue in revenue.";

【讨论】:

  • 正是我想要的! SO让我在几分钟内选择答案。谢谢!
【解决方案2】:

一种方法使用聚合:

select replace(replace('We found that [total_clicks] generated [total_revenue] in revenue.',
                       '[total_clicks]',
                       max(case when type = 'total_clicks' then value end)
                      ), '[total_revenue],
                      max(case when type = 'total_revenue' then value end)
              )
from statistics;

【讨论】:

  • 这肯定是一个意想不到的答案,但很有趣。
  • “我如何使用 PHP 来” - 我已经找到了一些使用 MySQL 的方法来做到这一点,如果可能的话只是尽量避免这种情况。
猜你喜欢
  • 2014-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 2015-01-16
  • 2016-12-31
  • 1970-01-01
相关资源
最近更新 更多