Example SELECT Query with Binding Variables

I'm trying to bind the input parameters into my SELECT query and then fetch the resulting rows, but MySQLi seems to be different from 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 so, how do I get strings into associative arrays? If I am exaggerating it, how should I proceed?

+2


a source to share


2 answers


mysqli does not provide a way to get the results into an array. If you want this functionality, you have two options:

  • extend mysqli and write fetchAll method
  • use pdo from now on
prompt

: use pdo



just trying to make your life easier.

read it

+3


a source


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;
}

      

+3


a source







All Articles