开发者

Example of SELECT query with bind variables

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开发者_如何学Go_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?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜