2013-04-19 2 views
1
/** 
    * Prepares and executes an SQL statement with bound data. 
    * 
    * @param mixed $sql The SQL statement with placeholders. 
    *      May be a string or Zend_Db_Select. 
    * @param mixed $bind An array of data to bind to the placeholders. 
    * @return Zend_Db_Statement_Interface 
    */ 
    public function query($sql, $bind = array()) 
     { 
      // connect to the database if needed 
      $this->_connect(); 

      // is the $sql a Zend_Db_Select object? 
      if ($sql instanceof Zend_Db_Select) { 
       if (empty($bind)) { 
        $bind = $sql->getBind(); 
       } 

       $sql = $sql->assemble(); 
      } 

      // make sure $bind to an array; 
      // don't use (array) typecasting because 
      // because $bind may be a Zend_Db_Expr object 
      if (!is_array($bind)) { 
       $bind = array($bind); 
      } 

      // prepare and execute the statement with profiling 
      $stmt = $this->prepare($sql); 
      $stmt->execute($bind); 

      // return the results embedded in the prepared statement object 
      $stmt->setFetchMode($this->_fetchMode); 
      return $stmt; 
     } 

code ci-dessus est de Zend/Db/Adapter/Abstract.php, bien qu'il y ait un commentaire, je ne comprends toujours pas l'utilisation de bind $. Si possible, veuillez expliquer avec un exemple.
Merci.Essayer de comprendre les requêtes de fonctions dans zend

Répondre

0

$bind est un argument de tableau pour les requêtes paramétrées:

// $bind with single param: 
$obj->query('SELECT * FROM TableName WHERE IDColumn = ?', array(1)); 
// OR 
$obj->query('SELECT * FROM TableName WHERE IDColumn = ?', 1); 

Moyens:

SELECT * FROM TableName WHERE IDColumn = 1 

// $bind with multiparams: 
$obj->query('SELECT * FROM TableName WHERE somefield BETWEEN ? AND ?', array(10, 15)); 

Moyens:

SELECT * FROM TableName WHERE somefield BETWEEN 10 AND 15 

// $bind omitted at all: 
$obj->query('SELECT * FROM TableName ORDER BY somefield'); 

Moyens:

SELECT * FROM TableName ORDER BY somefield 

Si $sql est instance de Zend_Db_Select, il peut avoir des propres liaisons. Donc, si fourni $bind est vide/omis, alors la liaison de $sql lui est affectée.

+0

Merci. très clair. – user2243528