Skip to content
Advertisement

How can I determine mySQL prepared statement result column names in PHP?

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.

Advertisement

Answer

I believe mysqli_stmt::result_metadata and mysqli_result::fetch_fields could help you.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement