* @package Mammut\DB */ class Statement extends Result implements iFetchable { /** * @var DB */ protected $db; /** * @var mixed */ protected $query; protected $limit; protected $skip; protected $rownr = 0; protected $executed = false; protected $affected = -1; /** * @var Result */ protected $result = NULL; /** * Generic statement emulation class. * * This class emulates the prepared statement behaviour. * * @param DB $database * The database link object * @param string $query * SQL query of the statement * @param integer $limit * Maximum number of rows returned * @param integer $skip * Skipping the first N rows */ public function __construct(DB $database, $query, $limit = -1, $skip = 0) { $this->db = $database; $this->query = $query; $this->limit = $limit; $this->skip = $skip; } /** * Executes the statement. * * @param array $param * The parameter values * @return boolean TRUE if the execute was successfull * @throws IllegalStateException If count($param) doesn't match the number of parameters in the SQL query */ public function execute(array $param = array()) { if(substr_count($this->query, '?') != count($param)) throw new IllegalStateException('Wrong parameter count, needs to be ' . substr_count($this->query, '?')); $parts = explode('?', $this->query); $newquery = ''; foreach($param as $p) { $newquery .= current($parts); $newquery .= $this->db->escapeValue($p); next($parts); } $newquery .= current($parts); $this->result = $this->db->query($newquery, $this->limit, $this->skip); if(is_bool($this->result)) $this->affected = $this->db->getAffectedRowCount(); $this->executed = true; return true; } public function getColumns() { return $this->result->getColumns(); } public function getColumnInfo($column) { return $this->result->getColumnInfo($column); } public function getColumnCount() { if(empty($this->result)) return -1; return $this->result->getColumnCount(); } public function getRowNumber() { if(empty($this->result)) return -1; return $this->rownr; } public function getRowCount() { if(empty($this->result)) return -1; if(is_bool($this->result)) return $this->affected; return $this->result->getRowCount(); } public function fetchRow() { return $this->result->fetchRow(); } public function fetchArray() { return $this->result->fetchArray(); } public function fetchObject($class = false, $param = array()) { return $this->result->fetchObject($class, $param); } /** * Frees all resources. */ public function free() { if(is_object($this->result)) $this->result->close(); $this->result = NULL; $this->executed = false; } /** * Closes the statement and frees all resources. * After calling this method, the statement cannot be used again. */ public function close() { $this->free(); } public function __destruct() { $this->close(); } }