open() public method

It does nothing if a DB connection has already been established.
public open ( )
 public function initialize()
 {
     require_once "vendor/autoload.php";
     define('YII_DEBUG', false);
     require_once "vendor/yiisoft/yii2/Yii.php";
     $application = new yii\console\Application(['id' => 'yii-benchmark', 'basePath' => __DIR__]);
     Author::$db = Book::$db = $this->db = new Connection(['dsn' => 'sqlite::memory:']);
     $this->db->open();
     Author::createTable();
     Book::createTable();
 }
 /**
  * @param  boolean $reset whether to clean up the test database
  * @param  boolean $open whether to open and populate test database
  * @throws \yii\base\InvalidParamException
  * @throws \yii\db\Exception
  * @throws \yii\base\InvalidConfigException
  * @return \yii\db\Connection
  */
 public function getConnection($reset = true, $open = true)
 {
     if (!$reset && $this->db) {
         return $this->db;
     }
     $db = new Connection();
     $db->dsn = $this->database['dsn'];
     if (isset($this->database['username'])) {
         $db->username = $this->database['username'];
         $db->password = $this->database['password'];
     }
     if (isset($this->database['attributes'])) {
         $db->attributes = $this->database['attributes'];
     }
     if ($open) {
         $db->open();
         $lines = explode(';', file_get_contents(\Yii::getAlias('@yii/rbac/schema-' . $this->driverName . '.sql')));
         foreach ($lines as $line) {
             if (trim($line) !== '') {
                 $db->pdo->exec($line);
             }
         }
     }
     $this->db = $db;
     return $db;
 }
 /**
  * @param  boolean            $reset whether to clean up the test database
  * @param  boolean            $open  whether to open and populate test database
  * @return \yii\db\Connection
  */
 public function getConnection($reset = true, $open = true)
 {
     if (!$reset && $this->db) {
         return $this->db;
     }
     $db = new \yii\db\Connection();
     $db->dsn = $this->database['dsn'];
     if (isset($this->database['username'])) {
         $db->username = $this->database['username'];
         $db->password = $this->database['password'];
     }
     if (isset($this->database['attributes'])) {
         $db->attributes = $this->database['attributes'];
     }
     if ($open) {
         $db->open();
         $lines = explode(';', file_get_contents($this->database['fixture']));
         foreach ($lines as $line) {
             if (trim($line) !== '') {
                 $db->pdo->exec($line);
             }
         }
     }
     $this->db = $db;
     return $db;
 }
 public static function search(array $input)
 {
     $connection = new Connection(['dsn' => 'mysql:host=localhost;dbname=work', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8']);
     $connection->open();
     /**запрос выбирает имя сети, агенства и сумму
      * с группировкой ао агенству и "ИТОГО"
      * из подзапроса суммы с границами по датам.
      * COALESCE() меняет сумму NULL на 0
      */
     $sql = 'SELECT agency_network.agency_network_name, agency.agency_name, COALESCE(sum(t.amount),0) AS sum
             FROM agency_network
             RIGHT JOIN agency
             ON agency_network.agency_network_id = agency.agency_network_id
             LEFT JOIN
               (SELECT amount, date, agency_id
               FROM billing WHERE date BETWEEN :startdate AND :enddate) t
                    ON t.agency_id=agency.agency_id
             GROUP BY agency_name WITH ROLLUP;';
     /*Привязываем параметры с датами, для исключения иньекций*/
     $command = $connection->createCommand($sql)->bindParam(':startdate', $startdate)->bindParam(':enddate', $enddate);
     $startdate = $input[date1];
     $enddate = $input[date2];
     $result = $command->queryAll();
     $connection->close();
     return $result;
 }
Beispiel #5
0
 /**
  * @return bool
  */
 public function hasConnect()
 {
     $connection = new Connection(['dsn' => "mysql:host={$this->host};dbname={$this->dbname}", 'username' => $this->username, 'password' => $this->password, 'charset' => $this->charset]);
     try {
         $connection->open();
         return true;
     } catch (\Exception $e) {
         return false;
     }
 }
Beispiel #6
0
 /**
  * Конфиг полученный из БД
  * */
 private function getConfigFromDb()
 {
     $dbConfig = $this->textConfig['components']['db'];
     $connection = new Connection(['dsn' => $dbConfig['dsn'], 'username' => $dbConfig['username'], 'password' => $dbConfig['password']]);
     $connection->open();
     $config = $connection->createCommand('SELECT * FROM settings')->queryAll();
     return ArrayHelper::map($config, 'name', 'value', function ($array) {
         return ArrayHelper::getValue($array, 'category');
     });
 }
Beispiel #7
0
 public function init()
 {
     parent::init();
     $host = '127.0.0.1';
     $dbname = 'tmc_test';
     $connection = new Connection(['dsn' => 'mysql:host=' . $host . ';dbname=' . $dbname, 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'tablePrefix' => 't_']);
     $connection->open();
     $this->db = $connection;
     if ($this->cache !== null) {
         $this->cache = Instance::ensure($this->cache, Cache::className());
     }
 }
 public function testOpenClose()
 {
     $connection = $this->getConnection(false, false);
     $this->assertFalse($connection->isActive);
     $this->assertEquals(null, $connection->pdo);
     $connection->open();
     $this->assertTrue($connection->isActive);
     $this->assertTrue($connection->pdo instanceof \PDO);
     $connection->close();
     $this->assertFalse($connection->isActive);
     $this->assertEquals(null, $connection->pdo);
     $connection = new Connection();
     $connection->dsn = 'unknown::memory:';
     $this->setExpectedException('yii\\db\\Exception');
     $connection->open();
 }
Beispiel #9
0
 /**
  * @inheritdoc
  */
 public static function getDb()
 {
     $host = '127.0.0.1';
     $dbname = 'tmc_test';
     $connection = new Connection(['dsn' => 'mysql:host=' . $host . ';dbname=' . $dbname, 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'tablePrefix' => 't_']);
     $connection->open();
     return $connection;
     //if (Configs::instance()->db !== null) {
     //    echo 'sdfdsf';
     //    exit;
     //    return Configs::instance()->db;
     //} else {
     //    echo 'xxxxx';
     //    exit;
     //    return parent::getDb();
     //}
 }
Beispiel #10
0
 /**
  * @throws \yii\base\InvalidParamException
  * @throws \yii\db\Exception
  * @throws \yii\base\InvalidConfigException
  * @return \yii\db\Connection
  */
 public static function getConnection()
 {
     if (static::$db == null) {
         $db = new Connection();
         $db->dsn = static::$database['dsn'];
         if (isset(static::$database['username'])) {
             $db->username = static::$database['username'];
             $db->password = static::$database['password'];
         }
         if (isset(static::$database['attributes'])) {
             $db->attributes = static::$database['attributes'];
         }
         if (!$db->isActive) {
             $db->open();
         }
         static::$db = $db;
     }
     return static::$db;
 }
Beispiel #11
0
 public function translation($table_name, $field_en, $field_ru)
 {
     $connect_param = ['dsn' => self::$db['dsn'], 'username' => self::$db['username'], 'password' => self::$db['password'], 'charset' => self::$db['charset']];
     $query = new Connection($connect_param);
     $query->open();
     $command = $query->createCommand('select ' . $field_en . ' from ' . $table_name . ' where ' . $field_ru . ' is null');
     $a = $command->queryAll();
     //        var_dump($a);die;
     foreach ($a as $r) {
         //            var_dump($r);die;
         $t = $this->translate_yandex($r[$field_en]);
         //            var_dump($t,111);die;
         if ($t != '') {
             //                $sql='UPDATE '.$table_name.' SET '.$field_ru.'='.$t.' WHERE '.$field_en.'='.$r[$field_en];
             $r = $command->update($table_name, [$field_ru => $t], $field_en . "='" . $r[$field_en] . "'")->execute();
             //var_dump($r);die;
             //                $this->createCommand($sql);
             //                ->update($table_name, [$field_en => $t], [$field_en => $r->$field_en])->execute();
         }
     }
 }
Beispiel #12
0
 private function checkDb()
 {
     self::_appendLog('检查数据库连接。。。');
     $dbHost = LuLu::getPostValue('dbHost');
     $dbName = LuLu::getPostValue('dbName');
     $dbUsername = LuLu::getPostValue('dbUsername');
     $dbPassword = LuLu::getPostValue('dbPassword');
     if (empty($dbHost) || empty($dbName) || empty($dbUsername)) {
         $message = '数据库信息必须填写完整';
         self::_appendLog($message, true);
         return false;
     }
     $config = ['dsn' => "mysql:host={$dbHost};dbname={$dbName}", 'username' => $dbUsername, 'password' => $dbPassword];
     $result = false;
     $message = '';
     $db = new Connection($config);
     try {
         $db->open();
         if (!$db->isActive) {
             $message = '连接失败,请检查数据库配置';
             $result = false;
         } else {
             $message = '数据库连接成功';
             $result = true;
         }
     } catch (Exception $e) {
         $db->close();
         $message = self::getDbError($e->getMessage(), ['dbHost' => $dbHost, 'dbName' => $dbName]);
         $result = false;
     }
     self::_appendLog($message, !$result);
     return $result;
 }
Beispiel #13
0
 /**
  * 检测数据库
  */
 private function checkDb()
 {
     $dbHost = LsYii::getPostValue('dbHost');
     $dbName = LsYii::getPostValue('dbName');
     $dbUsername = LsYii::getPostValue('dbUsername');
     $dbPassword = LsYii::getPostValue('dbPassword');
     self::_appendLog(LsYii::gT("开始检查数据库信息。。。"));
     $dbConfig = ["dsn" => "mysql:host={$dbHost};dbname={$dbName}", "username" => $dbUsername, "password" => $dbPassword];
     $db = new Connection($dbConfig);
     $result = false;
     try {
         $res = $db->open();
         if (!$db->isActive) {
             $message = LsYii::gT("数据库连接不上,请返回检测");
             $result = false;
         } else {
             $message = LsYii::gT("数据库信息正确");
             $result = true;
         }
     } catch (\Exception $ex) {
         $message = self::getDbError($ex->getMessage(), ['dbHost' => $dbHost, 'dbName' => $dbName]);
         $result = false;
     }
     self::_appendLog($message, !$result);
     return $result;
 }
Beispiel #14
0
//$platformid = 1000;
//$charid = 1000;
//$name = "aaaa";
//$type = 1000;
//$platform = "aaa";
//$version = 10000;
//$error = "您好";
//$curtime = "18:45:52";
$cursql = 'SELECT `cnt` FROM `netlogcount` WHERE `id`=' . $platformid . ';';
//$dataTableName = date("Y-m") . "-netlogdata";
$dataTableName = "netlogdata";
// 建立数据库连接
$connection = new Connection(['dsn' => $config['components']['db']['dsn'], 'username' => $config['components']['db']['username'], 'password' => $config['components']['db']['password']]);
$connection->charset = 'utf8';
// 这个字符集在 NetLogDB.php 中的配置不能赋值到这里
$connection->open();
// 检查数据库中记录数
$cntcmd = $connection->createCommand($cursql);
$retset = $cntcmd->queryOne();
if ($retset) {
    if (isset($retset['cnt'])) {
        // 执行插入操作
        $insertcmd = $connection->createCommand();
        $insertcmd->insert($dataTableName, ['charid' => $charid, 'name' => $name, 'time' => $curtime, 'type' => $type, 'platform' => $platform, 'version' => $version, 'error' => $error])->execute();
        // 更新计数
        $condition = '`id`=' . $platformid;
        $updatecmd = $connection->createCommand();
        $updatecmd->update('netlogcount', ['cnt' => $retset['cnt'] + 1], $condition)->execute();
    }
} else {
    // 执行插入操作
Beispiel #15
0
    public function actionPdf()
    {
        if (Yii::$app->request->get("ID_SOLICITUD")) {
            $ID_SOLICITUD = Html::encode($_GET["ID_SOLICITUD"]);
            $mpdf = new mPDF();
            $connection = new \yii\db\Connection(Yii::$app->db);
            $connection->open();
            $str = '<table border=0 cellspacing=0 cellpadding=2><tbody><tr><td><img src="http://www.ubiobio.cl/mcc/images/ubbdescargagradientesolo.png"/></td><td><h1>RENDICION DE GASTOS</h1><br>Fecha: ' . date("d-m-Y") . '</td></tr></table>';
            $mpdf->WriteHTML($str);
            ///////////////////////////////////////////////////////////////////
            $sql = "Select ID_SOLICITUD, ID_TIPO_DE_VIAJE, ID_VIAJE, FECHA_SOLICITUD, CUERPO_SOLICITUD from SOLICITUD_DE_VIAJE where ID_SOLICITUD=" . $ID_SOLICITUD;
            $command = $connection->createCommand($sql);
            $dataReader = $command->query();
            $str = "<h2>- SOLICITUD:</h2><table border=1 cellspacing=0 cellpadding=2><tbody><tr><td>ID</td><td>FECHA SOLICITUD</td><td>CUERPO SOLICITUD</td></tr>";
            $dos = 1;
            foreach ($dataReader as $row) {
                $ID_TIPO_DE_VIAJE = $row->ID_TIPO_DE_VIAJE;
                $str = $str . "<tr>";
                foreach ($row as $col) {
                    if ($dos == 2) {
                        $ID_TIPO_DE_VIAJE = $col;
                    } else {
                        if ($dos == 3) {
                            $ID_VIAJE = $col;
                        } else {
                            $str = $str . "<td>" . $col . "</td>";
                        }
                    }
                    $dos = $dos + 1;
                }
                $str = $str . "</tr>";
            }
            $str = $str . "</tbody></table>";
            $mpdf->WriteHTML($str);
            ///////////////////////////////////////////////////////////////////
            $sql = "Select * from TIPO_DE_VIAJE where ID_TIPO_DE_VIAJE='" . $ID_TIPO_DE_VIAJE . "'";
            $command = $connection->createCommand($sql);
            $dataReader = $command->query();
            $str = "<h2>- TIPO DE VIAJE DE LA SOLICITUD:</h2><table border=1 cellspacing=0 cellpadding=2><tbody><tr><td>ID</td><td>NOMBRE TIPO DE VIAJE</td><td>MONTO TIPO DE VIAJE</td></tr>";
            foreach ($dataReader as $row) {
                $str = $str . "<tr>";
                foreach ($row as $col) {
                    $str = $str . "<td>" . $col . "</td>";
                }
                $str = $str . "</tr>";
            }
            $str = $str . "</tbody></table>";
            $mpdf->WriteHTML($str);
            ///////////////////////////////////////////////////////////////////
            $sql = "Select * from VIAJE where ID_VIAJE='" . $ID_VIAJE . "'";
            $command = $connection->createCommand($sql);
            $dataReader = $command->query();
            $str = "<h2>- VIAJE DE LA SOLICITUD:</h2><table border=1 cellspacing=0 cellpadding=2><tbody><tr><td>ID</td><td>ORIGEN</td><td>FECHA INICIO</td><td>FECHA TERMINO</td></tr>";
            foreach ($dataReader as $row) {
                $str = $str . "<tr>";
                foreach ($row as $col) {
                    $str = $str . "<td>" . $col . "</td>";
                }
                $str = $str . "</tr>";
            }
            $str = $str . "</tbody></table>";
            $mpdf->WriteHTML($str);
            ///////////////////////////////////////////////////////////////////
            $sql = "Select ID_DESTINO, DURACION_VIAJE_DIAS, MEDIO_DE_TRANSPORTE, CIUDAD_DESTINO, PAIS_DESTINO from DESTINO where ID_VIAJE='" . $ID_VIAJE . "'";
            $command = $connection->createCommand($sql);
            $dataReader = $command->query();
            $str = "<h2>- DESTINO(S) DEL VIAJE:</h2><table border=1 cellspacing=0 cellpadding=2><tbody><tr><td>ID</td><td>DURACION</td><td>MEDIO DE TRANSPORTE</td><td>CIUDAD DESTINO</td><td>PAIS DESTINO</td></tr>";
            foreach ($dataReader as $row) {
                $str = $str . "<tr>";
                foreach ($row as $col) {
                    $str = $str . "<td>" . $col . "</td>";
                }
                $str = $str . "</tr>";
            }
            $str = $str . "</tbody></table>";
            $mpdf->WriteHTML($str);
            ///////////////////////////////////////////////////////////////////
            $sql = "Select ID_GASTO, NOMBRE_GASTO, MONTO_GASTO, FECHA_GASTO from GASTOS where ID_VIAJE='" . $ID_VIAJE . "'";
            $command = $connection->createCommand($sql);
            $dataReader = $command->query();
            $str = "<h2>- GASTO(s) ASOCIADOS AL VIAJE:</h2><table border=1 cellspacing=0 cellpadding=2><tbody><tr><td>ID</td><td>NOMBRE</td><td>MONTO</td><td>FECHA</td></tr>";
            $id_gasto = 1;
            foreach ($dataReader as $row) {
                $str = $str . "<tr>";
                foreach ($row as $col) {
                    if ($id_gasto == 1) {
                        $ID_GASTO = $col;
                    }
                    $id_gasto++;
                    $str = $str . "<td>" . $col . "</td>";
                }
                $str = $str . "</tr>";
            }
            $str = $str . "</tbody></table>";
            $mpdf->WriteHTML($str);
            ///////////////////////////////////////////////////////////////////
            $str = '<h2>- IMAGEN(ES) ASOCIADAS A CADA GASTO:</h2><p><img src="http://www.teacherclaudio.cl/wp-content/uploads/2014/07/Boleta_01.png"/></p>
<p><img src="http://am-sur.com/am-sur/peru/selva-m/Oxapampa-notizen-d/003-busbillet-Lobato-9-okt-2008.gif"/></p>
<p><img src="http://www.cosale.cl/wp-content/uploads/2013/10/boleta.jpg"/></p>
<p><img src="https://www.reclamos.cl/files/boleta_1_0.jpg"/></p>';
            $mpdf->WriteHTML($str);
            ///////////////////////////////////////////////////////////////////
            $mpdf->Output();
            $connection->close();
            exit;
        }
    }
 /**
  * Site "Home" page.
  */
 public function actionIndex()
 {
     $this->layout = 'main';
     $model = new DatabaseForm();
     $admin = new AdminForm();
     $mail = new MailForm();
     $model->setAttributes(Yii::$app->session->get('db'));
     $admin->setAttributes(Yii::$app->session->get('admin'));
     $mail->setAttributes(Yii::$app->session->get('mail'));
     if ($mail->load(Yii::$app->request->post()) && $mail->validate()) {
         if ($this->steps['active'] == 5) {
             $this->steps[$this->steps['active']] = ['icon' => 'check', 'valid' => true];
             $this->steps['active'] = 6;
         }
         $this->saveStep();
         $mail->set();
     }
     if ($admin->load(Yii::$app->request->post()) && $admin->validate()) {
         if ($this->steps['active'] == 5) {
             $this->steps[$this->steps['active']] = ['icon' => 'check', 'valid' => true];
             $this->steps['active'] = 6;
         }
         $this->saveStep();
         $admin->set();
     }
     if ($model->load(Yii::$app->request->post(), 'DatabaseChoose') && $model->validate(['type'])) {
         if ($this->steps['active'] == 3) {
             $this->steps[$this->steps['active']] = ['icon' => 'check', 'valid' => true];
             $this->steps['active'] = 4;
         }
         $this->saveStep();
         $model->set();
     }
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         $model->set();
         $dsn = $model->getDsn();
         try {
             $connection = new Connection(['dsn' => $dsn, 'username' => $model->user, 'password' => $model->password]);
             $connection->open();
             $model->createDb($connection);
             if ($this->steps['active'] == 4) {
                 $this->steps[$this->steps['active']] = ['icon' => 'check', 'valid' => true];
                 $this->steps['active'] = 5;
             }
             $this->saveStep();
         } catch (Exception $e) {
             $model->addError('', '<strong>' . Yii::t('install', 'When you connect to the database with the specified parameters errors occurred.') . '</strong><br />' . $dsn . '<br />' . $e->getMessage());
         }
     }
     if (Yii::$app->request->isPost && Yii::$app->request->post('step')) {
         $step = (int) Yii::$app->request->post('step') - 1;
         $currentStep = $this->steps['active'];
         $previousStep = $step - 1;
         if ($currentStep > $step && isset($this->steps[$currentStep]) && !$this->steps[$currentStep]['valid']) {
             unset($this->steps[$currentStep]);
         }
         if (isset($this->steps[$previousStep]) && $this->steps[$previousStep]['valid']) {
             if (isset($this->steps[$step])) {
                 $this->steps[$step]['icon'] = 'arrow-right';
             } else {
                 $this->steps[$step] = ['icon' => 'arrow-right', 'valid' => false];
             }
             if (isset($this->steps[$currentStep]) && $currentStep != $step) {
                 $this->steps[$currentStep]['icon'] = 'check';
             }
             $this->steps['active'] = $step;
             $this->saveStep();
         } else {
             if ($step == 0) {
                 $this->refreshStep();
             }
         }
     }
     return $this->render('index', ['steps' => $this->steps, 'model' => $model, 'admin' => $admin, 'mail' => $mail]);
 }