How to use prepared statements in Zend Framework

2019-02-18 04:25发布

问题:

Mysql supports prepared statements in this way:

http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html

Is there a support for it in Zend Framework (I couldn't find it), and how to use it. If not, how would you implement prepared statements as Zend Framework addon.

回答1:

$sql = "SELECT * FROM table_name WHERE id = :id ";

$stmt  = Zend_Registry::get("db")->prepare($sql);

$data=array(array('id'=> $id);

$stmt->execute($data);

print_r($stmt->fetchAll());


回答2:

You can try like this

$sql = "SELECT * FROM table_name WHERE id = :id'";
$stmt = new Zend_Db_Statement_Pdo($this->_db, $sql); 
$stmt->execute(array(':id' => $id));


回答3:

After some research, I didn't find ZF's support for prepared statements in this very same way. The only thing you can do is to emulate it as @Nikita Gopkalo posted.



回答4:

You should look at the zend documentation.

https://github.com/zendframework/zend-db/blob/master/doc/book/result-set.md

so here is a sample code.

<?php

use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\ResultSet;

$statement = $driver->createStatement('SELECT * FROM users');
$statement->prepare();
$result = $statement->execute($parameters);

if ($result instanceof ResultInterface && $result->isQueryResult()) {
  $resultSet = new ResultSet;
  $resultSet->initialize($result);

  foreach ($resultSet as $row) {
    echo $row->my_column . PHP_EOL;
  }
}

?>