tags:

views:

115

answers:

2

I'm trying to bind input parameters into my SELECT query and then fetch the resulting rows, but MySQLi seems to be different to other APIs I'm used to and I'm getting lost in the PHP manual.

Is the following approach correct?

$sql = 'SELECT product_id, product_name, area_id
    FROM product
    WHERE product_id = ?';
$stmt = $myMySQLi->prepare($sql);
if(!$stmt){
    throw new Exception('Prepare error');
}
if( !@$stmt->bind_param('i', $product_id) ){
    throw new Exception('Bind error');
}
if( !$stmt->execute() ){
    throw new Exception('Execute error');
}

If it's so, how do I fetch rows into associative arrays? If I'm overcomplicating it, how should I proceed?

+3  A: 

Using bind_result you can map results to variables:

$stmt->bind_result($product_id, $product_name, $area_id);
while ($stmt->fetch()) {
    echo $product_id . ": " . $product_name;
}
racetrack
Oh my... That's so primitive... It's the first time I use MySQLi and I already hate it to the bones. Thanks.
Álvaro G. Vicario
+3  A: 

mysqli doesn't provide a way to fetch results into an array. If you want this functionality you have two options:

  1. extend mysqli and write a fetchAll method
  2. use pdo from now on

hint: use pdo

just trying to make your life easier.

read this

Galen
I didn't mean all rows at a time, just row by row, like MySQLi_Result::fetch_assoc(). Thanks for the link: I couldn't find a way to obtain a MySQLi_Result from a MySQLi_STMT and it seems that...you cannot! Thank God the project is at an early stage and I can still get rid of MySQLi.
Álvaro G. Vicario
if you can go with pdo i highly recommend it.
Galen
I've discarded MySQLi. I can't delay this project any longer so I'll stick to my good old custom class built on top of regular MySQL functions. On next project I'll give PDO a try-out.
Álvaro G. Vicario