views:

424

answers:

2

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.

+1  A: 

I believe mysqli_result::fetch_object and mysqli_result::fetch_fields could help you.

Artem Barger
I don't believe you can get a result set out of a prepared statement can you? The only way I know how to get results back is with bind_results() and fetch()ing each row individually.
Adam A
Ah you're exactly correct! I can use $stmt->store_result()->fetch_fields()[columnIndex]->nameThank you very much!!!
Adam A
Correction:$stmt->store_result();$stmt->result_metadata()->fetch_fields()[columnIndex]->name;
Adam A
A: 

Thanks for this Correction. It's very useful when you have no choice in front of a 'select *' S.