如何在 PHP 中确定 mySQL 准备好的语句结果列名称?
也就是说,使用如下准备好的语句:
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类的正确属性。
That is, with a prepared statement like:
select col1,...coln from table where col3 = ?
I believe I can use $mysqli->field_count to get the number of columns being returned (haven't tried).
But is there a way to link each column name to the values returned in bind_results?
I could always try to parse the column names out from the command itself, but that's not a road I want to go down.
Context:
I want to be able to define a PHP interface that maps class properties to column names returned from the database. So given
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;}
}
and
$mysqli->prepare("select col0, col1, col2, col3 from table");
I can use bind_results and then do something like (pseudoish code)
for($resultColumns as $columnName) {
if(isset($map[$columnName])) $map[$columnName] = $results[$columnName];
}
to pull out just the two columns I need (col1 and col2) and assign them to the correct properties of class A.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信 mysqli_stmt::result_metadata 和 mysqli_result::fetch_fields 可以帮助你。
I believe mysqli_stmt::result_metadata and mysqli_result::fetch_fields could help you.