コード例 #1
0
ファイル: SqlException.php プロジェクト: cradlephp/packages
 /**
  * @covers Cradle\Sql\SqlException::forQueryError
  */
 public function testForQueryError()
 {
     $message = null;
     try {
         throw SqlException::forQueryError('foo', 'bar');
     } catch (SqlException $e) {
         $message = $e->getMessage();
     }
     $this->assertEquals('foo Query: bar', $message);
 }
コード例 #2
0
ファイル: AbstractSql.php プロジェクト: cradlephp/packages
 /**
  * Queries the database
  *
  * @param *string       $query The query to ran
  * @param array         $binds List of binded values
  * @param callable|null $fetch Whether to fetch all the rows
  *
  * @return array
  */
 public function query($query, array $binds = [], $fetch = null)
 {
     $request = new StdClass();
     $request->query = $query;
     $request->binds = $binds;
     $connection = $this->getConnection();
     $query = (string) $request->query;
     $stmt = $connection->prepare($query);
     //bind some more values
     foreach ($request->binds as $key => $value) {
         $stmt->bindValue($key, $value);
     }
     //PDO Execute
     if (!$stmt->execute()) {
         $error = $stmt->errorInfo();
         //unpack binds for the report
         foreach ($binds as $key => $value) {
             $query = str_replace($key, "'{$value}'", $query);
         }
         //throw Exception
         throw SqlException::forQueryError($query, $error[2]);
     }
     //clear binds
     $this->binds = [];
     if (!is_callable($fetch)) {
         $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
         //log query
         $this->log(['query' => $query, 'binds' => $binds, 'results' => $results]);
         return $results;
     }
     if ($fetch instanceof Closure) {
         $fetch = $fetch->bindTo($this, get_class($this));
     }
     while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
         if (call_user_func($fetch, $row, $this) === false) {
             break;
         }
     }
     return $this;
 }