【问题标题】:How can I determine mySQL prepared statement result column names in PHP?如何确定 PHP 中的 mySQL 准备语句结果列名?
【发布时间】:2009-06-19 07:13:33
【问题描述】:

也就是说,使用如下准备好的语句:

select col1,...coln from table where col3 = ?

我相信我可以使用 $mysqli->field_count 来获取返回的列数(没有尝试过)。

但是有没有办法将每个列名链接到 bind_results 中返回的值? 我总是可以尝试从命令本身中解析出列名,但这不是我想走的路。

上下文:

我希望能够定义一个 PHP 接口,将类属性映射到从数据库返回的列名。所以给定

class A implements IColumnMapped{
    public $prop1, $prop2; private $map;
    public function __construct() {
        $map = array();
        $map['col1'] = & $this->prop1;
        $map['col2'] = & $this->prop2;
    }
    public function getMap() { return $this->map;}
}

$mysqli->prepare("select col0, col1, col2, col3 from table");

我可以使用 bind_results 然后执行类似(伪代码)

for($resultColumns as $columnName) {
    if(isset($map[$columnName])) $map[$columnName] = $results[$columnName];
}

只提取我需要的两列(col1 和 col2)并将它们分配给 A 类的正确属性。

【问题讨论】:

    标签: php mysqli prepared-statement


    【解决方案1】:

    【讨论】:

    • 我不相信您可以从准备好的语句中获得结果集,可以吗?我知道如何取回结果的唯一方法是分别使用 bind_results() 和 fetch() 处理每一行。
    • 啊,你完全正确!我可以用 $stmt->store_result()->fetch_fields()[columnIndex]->name 非常感谢!!!
    • 更正:$stmt->store_result(); $stmt->result_metadata()->fetch_fields()[columnIndex]->name;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多