PDO PHP Class Code Examples

This page contains top rated real world PHP examples of class PDO extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: tbDatabase.php Project: freewayspb/TelegramSiteHelper
1
function tbDatabase()
{
    global $dbUse;
    try {
        if ($dbUse == "sqlite") {
            global $tbRootDir;
            $db = new PDO("sqlite:" . $tbRootDir . "/telegram.db");
        } elseif ($dbUse == "mysql") {
            global $mysqlHost, $mysqlDB, $mysqlLogin, $mysqlPassword;
            $db = new PDO("mysql:host=" . $mysqlHost . ";dbname=" . $mysqlDB, $mysqlLogin, $mysqlPassword);
        } else {
            return false;
        }
        // Таймаут ожидания блокировки на запись
        $db->setAttribute(PDO::ATTR_TIMEOUT, 55);
        // Дефолтный fetch - как ассоциативный массив
        $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_BOTH);
        if ($dbUse == "sqlite") {
            $db->exec('PRAGMA journal_mode=WAL;');
        }
        // Проверим наличие нужных таблиц в базе данных
        if ($dbUse == "sqlite") {
            $sth = $db->prepare("SELECT name FROM sqlite_master WHERE type=:type");
            $executeArray = array(":type" => "table");
        } elseif ($dbUse == "mysql") {
            $sth = $db->prepare("SHOW TABLES");
            $executeArray = array();
        }
        $sth->execute($executeArray);
        $tblsInDB = array();
        while ($answer = $sth->fetch()) {
            $tblsInDB[] = $answer[0];
        }
        $neededTables = array("tbManagers", "tbChats", "tbMessages");
        $createTables = false;
        foreach ($neededTables as $key => $value) {
            if (array_search($value, $tblsInDB) === false) {
                $createTables = true;
                break;
            }
        }
        if ($createTables == true) {
            if ($dbUse == "sqlite") {
                $db->exec("\r\n\t\t\t\t\t\t\t\tDROP TABLE IF EXISTS tbManagers;\r\n\t\t\t\t\t\t\t\tCREATE TABLE tbManagers (\r\n\t\t\t\t\t\t\t\t\tmId integer NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n\t\t\t\t\t\t\t\t\tmName text NULL,\r\n\t\t\t\t\t\t\t\t\tmBotChatId text NULL,\r\n\t\t\t\t\t\t\t\t\tmSiteChatId text NULL,\r\n\t\t\t\t\t\t\t\t\tmStatus integer(1) NULL\r\n\t\t\t\t\t\t\t\t);\r\n\r\n\t\t\t\t\t\t\t\tDROP TABLE IF EXISTS tbChats;\r\n\t\t\t\t\t\t\t\tCREATE TABLE tbChats (\r\n\t\t\t\t\t\t\t\t\tchId integer NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n\t\t\t\t\t\t\t\t\tchHash text NULL,\r\n\t\t\t\t\t\t\t\t\tchManager integer(10) NULL\r\n\t\t\t\t\t\t\t\t);\r\n\r\n\t\t\t\t\t\t\t\tDROP TABLE IF EXISTS tbMessages;\r\n\t\t\t\t\t\t\t\tCREATE TABLE tbMessages (\r\n\t\t\t\t\t\t\t\t\tmsgId integer NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n\t\t\t\t\t\t\t\t\tmsgChatId integer NULL,\r\n\t\t\t\t\t\t\t\t\tmsgFrom text NULL,\r\n\t\t\t\t\t\t\t\t\tmsgTime integer(12) NULL,\r\n\t\t\t\t\t\t\t\t\tmsgText text NULL\t\t\t\t\t\t\t\t\t \r\n\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t");
            } elseif ($dbUse == "mysql") {
                $db->exec("\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\tDROP TABLE IF EXISTS `tbChats`;\r\n\t\t\t\t\tCREATE TABLE IF NOT EXISTS `tbChats` (\r\n\t\t\t\t\t\t`chId` int(11) NOT NULL AUTO_INCREMENT,\r\n\t\t\t\t\t\t`chHash` varchar(50) DEFAULT NULL,\r\n\t\t\t\t\t\t`chManager` int(10) DEFAULT NULL,\r\n\t\t\t\t\t\tPRIMARY KEY (`chId`),\r\n\t\t\t\t\t\tKEY `chId` (`chId`)\r\n\t\t\t\t\t) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;\r\n\r\n\t\t\t\t\tDROP TABLE IF EXISTS `tbManagers`;\r\n\t\t\t\t\tCREATE TABLE IF NOT EXISTS `tbManagers` (\r\n\t\t\t\t\t\t`mId` int(10) NOT NULL AUTO_INCREMENT,\r\n\t\t\t\t\t\t`mName` text,\r\n\t\t\t\t\t\t`mBotChatId` text,\r\n\t\t\t\t\t\t`mSiteChatId` text,\r\n\t\t\t\t\t\t`mStatus` int(1) DEFAULT NULL,\r\n\t\t\t\t\t\tPRIMARY KEY (`mId`),\r\n\t\t\t\t\t\tKEY `mId` (`mId`)\r\n\t\t\t\t\t) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;\r\n\r\n\r\n\t\t\t\t\tDROP TABLE IF EXISTS `tbMessages`;\r\n\t\t\t\t\tCREATE TABLE IF NOT EXISTS `tbMessages` (\r\n\t\t\t\t\t\t`msgId` int(10) NOT NULL AUTO_INCREMENT,\r\n\t\t\t\t\t\t`msgChatId` int(10) DEFAULT NULL,\r\n\t\t\t\t\t\t`msgFrom` varchar(5) DEFAULT NULL,\r\n\t\t\t\t\t\t`msgTime` varchar(12) DEFAULT NULL,\r\n\t\t\t\t\t\t`msgText` text,\r\n\t\t\t\t\t\tPRIMARY KEY (`msgId`),\r\n\t\t\t\t\t\tKEY `msgId` (`msgId`)\r\n\t\t\t\t\t) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;\r\n\r\n\r\n\t\t\t\t\t");
            }
        }
        return $db;
    } catch (PDOException $e) {
        return false;
    }
}
Example #2
Show file File: LoggerAppenderPDOTest.php Project: sacredwebsite/scalr
0
 /** Tests old-style logging using the $sql variable. */
 public function testOldStyle()
 {
     if (!extension_loaded('pdo_sqlite')) {
         self::markTestSkipped("Please install 'pdo_sqlite' in order to run this test");
     }
     // Create table with different column order
     $db = new PDO(self::dsn);
     $db->exec('CREATE TABLE unittest3 (ts timestamp, level varchar(32), msg varchar(64))');
     // Prepare appender
     $appender = new LoggerAppenderPDO("myname");
     $appender->setDSN(self::dsn);
     $appender->setCreateTable(false);
     $appender->setSql("INSERT INTO unittest3 (ts, level, msg) VALUES ('%d', '%p', '%m')");
     $appender->activateOptions();
     // Action!
     $event = new LoggerLoggingEvent("LoggerAppenderPDOTest", new Logger("TEST"), LoggerLevel::getLevelError(), "testmessage");
     $appender->append($event);
     // Check
     $db = new PDO(self::dsn);
     $result = $db->query("SELECT * FROM unittest3");
     self::assertFalse($result === false);
     $row = $result->fetch(PDO::FETCH_OBJ);
     self::assertTrue(is_object($row));
     self::assertEquals(1, preg_match('/^\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d.\\d\\d\\d$/', $row->ts));
     self::assertEquals('ERROR', $row->level);
     self::assertEquals('testmessage', $row->msg);
 }
Example #3
Show file File: proxy.php Project: sjayashree01/CMV_addWMSLayer_Widget
0
 public function getRateMeterDatabase()
 {
     try {
         if (file_exists($this->dbname)) {
             $db = new PDO("sqlite:" . $this->dbname);
             $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
             $this->con = $db;
             return;
         }
     } catch (ErrorException $e) {
         $this->proxyLog->log($e->getMessage());
         return null;
     }
     try {
         $db = new PDO("sqlite:" . $this->dbname);
         $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         chmod($this->dbname, 0777);
         if ($db != null) {
             $db->beginTransaction();
             $this->createResourceIpTable($db);
             $this->createClicksTable($db);
             $this->insertClickRecord($db);
             $db->commit();
             $this->con = $db;
         }
         return;
     } catch (PDOException $e) {
         $this->proxyLog->log($e->getMessage());
         return null;
     }
 }
Example #4
Show file File: AmtcwebInstaller.php Project: maratoid/amtc
0
 static function writeAmtcwebConfig($userData)
 {
     if (file_exists(AMTC_CFGFILE)) {
         echo 'INSTALLTOOL_LOCKED';
         return;
     }
     $wanted = array('TIMEZONE' => preg_replace('/[^A-Za-z\\/]/', '', $userData['timezone']), 'AMTCBIN' => realpath($userData['amtcbin']), 'AUTHURL' => $userData['authurl'], 'DBTYPE' => preg_replace('/[^A-Za-z]/', '', $userData['selectedDB']), 'DATADIR' => realpath($userData['datadir']));
     if ($wanted['TIMEZONE'] && $wanted['DATADIR'] && $wanted['DBTYPE'] && $wanted['AMTCBIN']) {
         $x = array("message" => "Configuration written successfully");
         if ($wanted['DBTYPE'] == 'SQLite') {
             // create db if non-existant
             umask(0);
             @touch($_POST['sqlitePath']);
             // grr should be called sqlitefile not path
             $wanted['SQLITEPATH'] = realpath($_POST['sqlitePath']);
             $wanted['PDOSTRING'] = sprintf('sqlite:%s', $wanted['SQLITEPATH']);
             $wanted['DBUSER'] = '';
             $wanted['DBPASS'] = '';
             $dbh = new PDO($wanted['PDOSTRING']);
         }
         if ($wanted['DBTYPE'] == 'MySQL') {
             // mysql://user:pass@host[:port]/dbname)
             $wanted['DBUSER'] = $_POST['mysqlUser'];
             $wanted['DBPASS'] = $_POST['mysqlPassword'];
             $mHost = $_POST['mysqlHost'];
             $mDB = $_POST['mysqlDB'];
             $wanted['PDOSTRING'] = sprintf('mysql:host=%s;dbname=%s', $mHost, $mDB);
             $tmp = new PDO(sprintf('mysql:host=%s', $mHost), $wanted['DBUSER'], $wanted['DBPASS']);
             $tmp->exec('CREATE DATABASE IF NOT EXISTS ' . $mDB . ';');
             $tmp = NULL;
             $dbh = new PDO($wanted['PDOSTRING'], $wanted['DBUSER'], $wanted['DBPASS']);
         }
         // stuff below will only happen if PDO connect was ok...
         $cfg = sprintf(self::$cfgTpl, $wanted['PDOSTRING'], $wanted['DBUSER'], $wanted['DBPASS'], $wanted['AMTCBIN'], $wanted['AUTHURL'], $wanted['TIMEZONE'], $wanted['DATADIR']);
         if (!is_writable(dirname(AMTC_CFGFILE))) {
             $x = array("errorMsg" => "Config directory " . AMTC_CFGFILE . " not writable!");
         } elseif (false === file_put_contents(AMTC_CFGFILE, $cfg)) {
             $x = array("errorMsg" => "Could not write config file!");
         } else {
             $selectedDB = strtolower($wanted['DBTYPE']);
             $dbh->exec(file_get_contents('lib/install-db/' . $selectedDB . '.sql'));
             $dbh->exec(file_get_contents('lib/install-db/' . $selectedDB . '-minimal.sql'));
             if ($_POST['importDemo'] == 'true') {
                 $dbh->exec(file_get_contents('lib/install-db/' . $selectedDB . '-exampledata.sql'));
             }
             // fix-me: add some sanitization ... and error checking ... and stuff!!!
         }
     } else {
         $x = $wanted['AMTCBIN'] ? array("errorMsg" => "Insufficient parameters!") : array("errorMsg" => "amtc binary not found at path provided");
     }
     return json_encode($x);
 }
Example #5
Show file File: install.php Project: buggithubs/FreshRSS
0
function checkBD()
{
    $ok = false;
    try {
        $str = '';
        $driver_options = null;
        switch ($_SESSION['bd_type']) {
            case 'mysql':
                $driver_options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
                try {
                    // on ouvre une connexion juste pour créer la base si elle n'existe pas
                    $str = 'mysql:host=' . $_SESSION['bd_host'] . ';';
                    $c = new PDO($str, $_SESSION['bd_user'], $_SESSION['bd_password'], $driver_options);
                    $sql = sprintf(SQL_CREATE_DB, $_SESSION['bd_base']);
                    $res = $c->query($sql);
                } catch (PDOException $e) {
                }
                // on écrase la précédente connexion en sélectionnant la nouvelle BDD
                $str = 'mysql:host=' . $_SESSION['bd_host'] . ';dbname=' . $_SESSION['bd_base'];
                break;
            case 'sqlite':
                $str = 'sqlite:' . join_path(USERS_PATH, $_SESSION['default_user'], 'db.sqlite');
                $driver_options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
                break;
            default:
                return false;
        }
        $c = new PDO($str, $_SESSION['bd_user'], $_SESSION['bd_password'], $driver_options);
        if (defined('SQL_CREATE_TABLES')) {
            $sql = sprintf(SQL_CREATE_TABLES, $_SESSION['bd_prefix_user'], _t('gen.short.default_category'));
            $stm = $c->prepare($sql);
            $ok = $stm->execute();
        } else {
            global $SQL_CREATE_TABLES;
            if (is_array($SQL_CREATE_TABLES)) {
                $ok = true;
                foreach ($SQL_CREATE_TABLES as $instruction) {
                    $sql = sprintf($instruction, $_SESSION['bd_prefix_user'], _t('gen.short.default_category'));
                    $stm = $c->prepare($sql);
                    $ok &= $stm->execute();
                }
            }
        }
    } catch (PDOException $e) {
        $ok = false;
        $_SESSION['bd_error'] = $e->getMessage();
    }
    if (!$ok) {
        @unlink(join_path(DATA_PATH, 'config.php'));
    }
    return $ok;
}
Example #6
Show file File: testconnection.php Project: joshjim27/jobsglobal
0
function connect($host, $client_db_name, $username, $password, $port, $driver = 'mysql')
{
    $keys = array('mysql' => array("host" => "host", "dbname" => "dbname", "port" => ";port="), 'sqlsrv' => array("host" => "Server", "dbname" => "Database", "port" => ","));
    if (strpos($host, "/") !== FALSE) {
        if (strpos($host, ":") !== FALSE) {
            //localhost:socket_dir
            $parts = explode(":", $host);
            $host = $keys[$driver]["host"] . "=" . $parts[0];
            $unix_socket = ";unix_socket=" . $parts[1];
        } else {
            //socket_dir
            $unix_socket = "unix_socket={$host}";
            $host = '';
        }
    } else {
        //clean host
        $unix_socket = '';
        $host = $keys[$driver]["host"] . "={$host}";
    }
    $error = false;
    if ($port != '') {
        $port = $keys[$driver]["port"] . "{$port};";
    } else {
        $port = ";";
    }
    $dbname = $keys[$driver]["dbname"] . "=";
    $dsn = "{$driver}:{$host}{$unix_socket}{$port}{$dbname}{$client_db_name}";
    try {
        $dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => false));
    } catch (PDOException $e) {
        //self::freichat_debug("unable to connect to database. Error : " . $e->getMessage());
        $error = $e->getMessage();
    }
    if (!$error) {
        return array($dsn, true);
    }
    $dbh = null;
    //reset connection;
    //if in localhost , host cannot be localhost for unix
    $_error = false;
    $host = $keys[$driver]["host"] . "=127.0.0.1";
    $dsn = "{$driver}:{$host}{$unix_socket}{$port}{$dbname}{$client_db_name}";
    try {
        $dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => false));
    } catch (PDOException $e) {
        //self::freichat_debug("unable to connect to database. Error : " . $e->getMessage());
        $_error = $e->getMessage();
    }
    if (!$_error) {
        return array($dsn, true);
    }
    return array($error, false);
}
Example #7
Show file File: dbpdo_pgsql.php Project: ijustyce/zblogphp
0
 /**
  * 连接数据库
  * @param array $array 数据库连接配置
  *              $array=array(
  *                  'pgsql_server',
  *                  'pgsql_username',
  *                  'pgsql_password',
  *                  'pgsql_name',
  *                  'pgsql_pre',
  *                  'pgsql_port',
  *                  'persistent')
  *                  )
  * @return bool
  */
 function Open($array)
 {
     $s = "pgsql:host={$array[0]};port={$array[5]};dbname={$array[3]};user={$array[1]};password={$array[2]};options='--client_encoding=UTF8'";
     if (false == $array[5]) {
         $db_link = new PDO($s);
     } else {
         $db_link = new PDO($s, null, null, array(PDO::ATTR_PERSISTENT => true));
     }
     $this->db = $db_link;
     $this->dbpre = $array[4];
     return true;
 }
Example #8
Show file File: MySQLHandler.php Project: Grprashanthkumar/ColfusionWeb
0
 public function getConnection()
 {
     if (is_null($this->database)) {
         $pdo = new PDO("mysql:host={$this->host};port={$this->port}", $this->user, $this->password);
     } else {
         $pdo = new PDO("mysql:host={$this->host};port={$this->port};dbname={$this->database};charset=utf8;", $this->user, $this->password);
     }
     //var_dump("mysql:host=$this->host;port=$this->port;dbname=$this->database;charset=utf8;", $this->user, $this->password);
     $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     return $pdo;
 }
Example #9
Show file File: DC437TestCase.php Project: dracony/forked-php-orm-benchmark
0
 private function prepareConnections()
 {
     // Establish two new individual connections
     $dsn = 'sqlite::memory:';
     $dbh = new PDO($dsn);
     $this->manager->openConnection($dbh, 'conn1', false);
     $dsn = 'sqlite::memory:';
     $dbh = new PDO($dsn);
     $this->manager->openConnection($dbh, 'conn2', false);
 }
Example #10
Show file File: smart_ajax.php Project: joshjim27/jobsglobal
0
 function connect($host, $client_db_name, $username, $password, $port, $driver = 'mysql')
 {
     if (!extension_loaded('PDO') || !extension_loaded('pdo_' . $driver)) {
         return array("pdo_" . $driver . " driver is not installed or enabled", false);
     }
     $keys = array('mysql' => array("host" => "host", "dbname" => "dbname", "port" => ";port="), 'sqlsrv' => array("host" => "Server", "dbname" => "Database", "port" => ","));
     if (strpos($host, "/") !== FALSE) {
         if (strpos($host, ":") !== FALSE) {
             //localhost:socket_dir
             $parts = explode(":", $host);
             $host = $keys[$driver]["host"] . "=" . $parts[0];
             $unix_socket = ";unix_socket=" . $parts[1];
         } else {
             //socket_dir
             $unix_socket = "unix_socket={$host}";
             $host = '';
         }
     } else {
         //clean host
         $unix_socket = '';
         $host = $keys[$driver]["host"] . "={$host}";
     }
     $error = false;
     if ($port != '') {
         $port = $keys[$driver]["port"] . "{$port};";
     } else {
         $port = ";";
     }
     $dbname = $keys[$driver]["dbname"] . "=";
     $dsn = "{$driver}:{$host}{$unix_socket}{$port}{$dbname}{$client_db_name}";
     try {
         $dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => false));
     } catch (PDOException $e) {
         //self::freichat_debug("unable to connect to database. Error : " . $e->getMessage());
         $error = $e->getMessage();
     }
     if (!$error) {
         return array($dsn, true);
     }
     $dbh = null;
     //reset connection;
     //if in localhost , host cannot be localhost for unix
     $_error = false;
     $host = $keys[$driver]["host"] . "=127.0.0.1";
     $dsn = "{$driver}:{$host}{$unix_socket}{$port}{$dbname}{$client_db_name}";
     try {
         $dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => false));
     } catch (PDOException $e) {
         //self::freichat_debug("unable to connect to database. Error : " . $e->getMessage());
         $_error = $e->getMessage();
     }
     if (!$_error) {
         return array($dsn, true);
     }
     return array($error, false);
 }
Example #11
Show file File: Base.php Project: Folcky/kanboard
0
 public function setUp()
 {
     date_default_timezone_set('UTC');
     if (DB_DRIVER === 'mysql') {
         $pdo = new PDO('mysql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
         $pdo->exec('DROP DATABASE ' . DB_NAME);
         $pdo->exec('CREATE DATABASE ' . DB_NAME);
         $pdo = null;
     } elseif (DB_DRIVER === 'postgres') {
         $pdo = new PDO('pgsql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
         $pdo->exec('DROP DATABASE ' . DB_NAME);
         $pdo->exec('CREATE DATABASE ' . DB_NAME . ' WITH OWNER ' . DB_USERNAME);
         $pdo = null;
     }
     $this->container = new Pimple\Container();
     $this->container->register(new Kanboard\ServiceProvider\DatabaseProvider());
     $this->container->register(new Kanboard\ServiceProvider\ClassProvider());
     $this->container['dispatcher'] = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
     $this->container['db']->logQueries = true;
     $this->container['logger'] = new Logger();
     $this->container['logger']->setLogger(new File($this->isWindows() ? 'NUL' : '/dev/null'));
     $this->container['httpClient'] = new FakeHttpClient();
     $this->container['emailClient'] = $this->getMockBuilder('EmailClient')->setMethods(array('send'))->getMock();
     $this->container['userNotificationType'] = $this->getMockBuilder('\\Kanboard\\Model\\UserNotificationType')->setConstructorArgs(array($this->container))->setMethods(array('getType', 'getSelectedTypes'))->getMock();
     $this->container['sessionStorage'] = new SessionStorage();
     $this->container['flash'] = function ($c) {
         return new FlashMessage($c);
     };
 }
Example #12
Show file File: connect.php Project: bassels/was-du-brauchst
0
function connect($database, $dbuser, $dbpass, $environment)
{
    switch ($environment) {
        case 'local':
            ini_set('display_errors', 1);
            error_reporting(E_ALL);
            try {
                $db = new PDO('mysql:host=localhost;dbname=' . $database . ';charset=utf8', $dbuser, $dbpass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
            } catch (PDOException $error) {
                echo 'Connection failed: ' . $error->getMessage();
            }
            break;
        case 'staging':
            try {
                $db = new PDO('mysql:host=localhost;dbname=' . $database . ';charset=utf8', $dbuser, $dbpass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
            } catch (PDOException $error) {
                echo 'Connection failed: ' . $error->getMessage();
            }
            break;
        case 'live':
            // connection with live server
            try {
                $db = new PDO('mysql:host=localhost;dbname=' . $database . ';charset=utf8', $dbuser, $dbpass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
            } catch (PDOException $error) {
                echo 'Connection failed: ' . $error->getMessage();
            }
            break;
        default:
            // case if environment constant is not set or in a wrong way (error in config.php)
            die('Something went incredibly wrong...');
            break;
    }
    return $db;
}
Example #13
Show file File: sqlite.inc.php Project: xVirusproj3ct/site_web_phf
0
 function Sql_connect($database = 'bdd')
 {
     $message = "";
     $continue = true;
     if ($database == '') {
         $database = $GLOBALS['db'];
     }
     if ($continue) {
         if (file_exists(DIR . 'data/' . $database) && empty($GLOBALS['db_link'])) {
             try {
                 $db = new PDO('sqlite:' . DIR . 'data/' . $database, '', '', array(PDO::ATTR_PERSISTENT => true));
             } catch (PDOException $error) {
                 print "error1 : " . $error->getMessage() . "<br/>";
                 die;
             }
         }
         if (file_exists('../data/' . $database) && empty($GLOBALS['db_link'])) {
             try {
                 $db = new PDO('sqlite:../data/' . $database, '', '', array(PDO::ATTR_PERSISTENT => true));
             } catch (PDOException $error) {
                 print "error2: " . $error->getMessage() . "<br/>";
                 die;
             }
         }
     }
     return $db;
     exit;
 }
Example #14
Show file File: install.php Project: christianesperar/openshift-processwire
0
 /**
  * Create database
  * 
  * Note: only handles database names that stick to ascii _a-zA-Z0-9.
  * For database names falling outside that set, they should be created
  * ahead of time. 
  * 
  * Contains contributions from @plauclair PR #950
  * 
  * @param string $dsn
  * @param array $values
  * @param array $driver_options
  * @return PDO|null
  * 
  */
 protected function dbCreateDatabase($dsn, $values, $driver_options)
 {
     $dbCharset = preg_replace('/[^a-z0-9]/', '', strtolower(substr($values['dbCharset'], 0, 64)));
     $dbName = preg_replace('/[^_a-zA-Z0-9]/', '', substr($values['dbName'], 0, 64));
     $dbNameTest = str_replace('_', '', $dbName);
     if (ctype_alnum($dbNameTest) && $dbName === $values['dbName'] && ctype_alnum($dbCharset) && $dbCharset === $values['dbCharset']) {
         // valid database name with no changes after sanitization
         try {
             $dsn2 = "mysql:host={$values['dbHost']};port={$values['dbPort']}";
             $database = new PDO($dsn2, $values['dbUser'], $values['dbPass'], $driver_options);
             $database->exec("CREATE SCHEMA IF NOT EXISTS `{$dbName}` DEFAULT CHARACTER SET `{$dbCharset}`");
             // reconnect
             $database = new PDO($dsn, $values['dbUser'], $values['dbPass'], $driver_options);
             if ($database) {
                 $this->ok("Created database: {$dbName}");
             }
         } catch (Exception $e) {
             $this->err("Failed to create database with name {$dbName}");
             $this->err($e->getMessage());
             $database = null;
         }
     } else {
         $database = null;
         $this->err("Unable to create database with that name. Please create the database with another tool and try again.");
     }
     return $database;
 }
Example #15
Show file File: SolubleTestFactories.php Project: belgattitude/soluble-schema
0
 /**
  * 
  * @param string $type
  * @param string|database
  * @return PDO|Mysqli
  */
 public static function getDbConnection($type, $config = null, $charset = "UTF8")
 {
     if ($config === null) {
         $config = self::getDbConfiguration($type);
     }
     $hostname = $config['hostname'];
     $username = $config['username'];
     $password = $config['password'];
     $database = isset($config['database']) ? $config['database'] : null;
     switch ($type) {
         case 'pdo:mysql':
             $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$charset}");
             if ($database === null) {
                 $conn = new PDO("mysql:host={$hostname}", $username, $password, $options);
             } else {
                 $conn = new PDO("mysql:host={$hostname};dbname={$database}", $username, $password, $options);
             }
             break;
         case 'mysqli':
             $conn = new \mysqli($hostname, $username, $password, $database);
             $conn->set_charset($charset);
             break;
         default:
             throw new \Exception(__METHOD__ . " Unsupported driver type ({$type})");
     }
     return $conn;
 }
Example #16
Show file File: connect.php Project: cyrilix/rompr
0
function probe_database()
{
    // In the case where collection_type is not set, probe to see which type of DB to use
    // This keeps the behaviour the same as previous versions which auto-detected
    // the database type. This does mean we get some duplicate code but this is
    // so much better for the user.
    global $mysqlc, $prefs;
    debuglog("Attempting to connect to MYSQL Server", "SQL_CONNECT", 4);
    try {
        $dsn = "mysql:host=" . $prefs['mysql_host'] . ";port=" . $prefs['mysql_port'] . ";dbname=" . $prefs['mysql_database'];
        $mysqlc = new PDO($dsn, $prefs['mysql_user'], $prefs['mysql_password']);
        debuglog("Connected to MySQL", "SQL_CONNECT", 5);
        $prefs['collection_type'] = 'mysql';
    } catch (Exception $e) {
        debuglog("Couldn't connect to MySQL - " . $e, "SQL_CONNECT", 3);
        $mysqlc = null;
    }
    if ($mysqlc == null) {
        debuglog("Attempting to use SQLite Database", 4);
        try {
            $dsn = "sqlite:prefs/collection_mpd.sq3";
            $mysqlc = new PDO($dsn);
            debuglog("Connected to SQLite", "MYSQL");
            $prefs['collection_type'] = 'sqlite';
        } catch (Exception $e) {
            debuglog("Couldn't use SQLite Either - " . $e, "MYSQL", 3);
            $mysqlc = null;
        }
    }
}
Example #17
Show file File: CashierReceiver.php Project: noikiy/posco-laravel-server
0
 public static function logToReceiptRecords($f)
 {
     $file_db = new PDO('sqlite:' . $f);
     $file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $result = $file_db->query('SELECT * FROM transactions;');
     $receiptNO = "";
     foreach ($result as $m) {
         $receiptNo = $m["receiptNo"];
     }
     $receiptlines = ReceiptLine::where('receiptNo', $receiptNo)->get();
     foreach ($receiptlines as $receiptline) {
         ReceiptLine::destroy($receiptline->id);
     }
     $receiptRecords = Receiptrecord::where(['receiptNo' => $receiptNo, 'progress' => '提供済み'])->get();
     foreach ($receiptRecords as $receiptRecord) {
         $receiptRecord->payment_id = $m['payment_id'];
         $receiptRecord->progress = "支払い済み";
         $receiptRecord->save();
     }
     $file_db = new PDO('sqlite:' . $f);
     $file_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $result = $file_db->query('SELECT * FROM payments;');
     foreach ($result as $m) {
         $payment = new Payment();
         $payment->price = $m["price"];
         $payment->payment = $m["payment"];
         $payment->changes = $m["changes"];
         $payment->time = $m["time"];
         $payment->uuid = $m["uuid"];
         $payment->shopName = $m["shopName"];
         $payment->employeeName = $m["employeeName"];
         $payment->save();
     }
     //        unlink($f);
 }
Example #18
Show file File: Base.php Project: perburn/kanboard
0
 public function setUp()
 {
     date_default_timezone_set('UTC');
     if (DB_DRIVER === 'mysql') {
         $pdo = new PDO('mysql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
         $pdo->exec('DROP DATABASE ' . DB_NAME);
         $pdo->exec('CREATE DATABASE ' . DB_NAME);
         $pdo = null;
     } elseif (DB_DRIVER === 'postgres') {
         $pdo = new PDO('pgsql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
         $pdo->exec('DROP DATABASE ' . DB_NAME);
         $pdo->exec('CREATE DATABASE ' . DB_NAME . ' WITH OWNER ' . DB_USERNAME);
         $pdo = null;
     }
     $this->container = new Pimple\Container();
     $this->container->register(new Kanboard\ServiceProvider\AuthenticationProvider());
     $this->container->register(new Kanboard\ServiceProvider\DatabaseProvider());
     $this->container->register(new Kanboard\ServiceProvider\ClassProvider());
     $this->container->register(new Kanboard\ServiceProvider\NotificationProvider());
     $this->container->register(new Kanboard\ServiceProvider\RouteProvider());
     $this->container['dispatcher'] = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
     $this->container['db']->logQueries = true;
     $this->container['logger'] = new Logger();
     $this->container['logger']->setLogger(new File($this->isWindows() ? 'NUL' : '/dev/null'));
     $this->container['httpClient'] = $this->getMockBuilder('\\Kanboard\\Core\\Http\\Client')->setConstructorArgs(array($this->container))->setMethods(array('get', 'getJson', 'postJson', 'postForm'))->getMock();
     $this->container['emailClient'] = $this->getMockBuilder('\\Kanboard\\Core\\Mail\\Client')->setConstructorArgs(array($this->container))->setMethods(array('send'))->getMock();
     $this->container['userNotificationType'] = $this->getMockBuilder('\\Kanboard\\Model\\UserNotificationType')->setConstructorArgs(array($this->container))->setMethods(array('getType', 'getSelectedTypes'))->getMock();
     $this->container['objectStorage'] = $this->getMockBuilder('\\Kanboard\\Core\\ObjectStorage\\FileStorage')->setConstructorArgs(array($this->container))->setMethods(array('put', 'moveFile', 'remove', 'moveUploadedFile'))->getMock();
     $this->container['sessionStorage'] = new SessionStorage();
     $this->container->register(new ActionProvider());
     $this->container['flash'] = function ($c) {
         return new FlashMessage($c);
     };
 }
Example #19
Show file File: form_throttle.php Project: gkionify/alfa-omega-licious
0
function formthrottle_too_many_submissions($ip)
{
    $tooManySubmissions = false;
    try {
        if (in_array("sqlite", PDO::getAvailableDrivers(), TRUE)) {
            $db = new PDO('sqlite:muse-throttle-db.sqlite3');
        } else {
            if (function_exists("sqlite_open")) {
                $db = new PDO('sqlite2:muse-throttle-db');
            }
        }
    } catch (PDOException $Exception) {
        return $tooManySubmissions;
    }
    if ($db) {
        $res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';");
        if (!$res or $res->fetchColumn() == 0) {
            $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)");
        }
        $db->exec("DELETE FROM Submission_History WHERE Submission_Date < DATETIME('now','-2 hours')");
        $stmt = $db->prepare("INSERT INTO Submission_History (IP,Submission_Date) VALUES (:ip, DATETIME('now'))");
        $stmt->bindParam(':ip', $ip);
        $stmt->execute();
        $stmt->closeCursor();
        $stmt = $db->prepare("SELECT COUNT(1) FROM Submission_History WHERE IP = :ip;");
        $stmt->bindParam(':ip', $ip);
        $stmt->execute();
        if ($stmt->fetchColumn() > 25) {
            $tooManySubmissions = true;
        }
        // Close file db connection
        $db = null;
    }
    return $tooManySubmissions;
}
Example #20
Show file File: _global.php Project: greboid/servicing
0
function makeConnection($connection_name = '')
{
    global $connections;
    if ($connection_name == '') {
        return "No connection type given";
        exit;
    }
    unset($db);
    $driver = $connections[$connection_name]['driver'];
    $dbhost = $connections[$connection_name]['dbhost'];
    $dbname = $connections[$connection_name]['dbname'];
    $dbuser = $connections[$connection_name]['dbuser'];
    $dbpassword = $connections[$connection_name]['dbpassword'];
    if (strlen($dbhost) > 0) {
        try {
            if ($driver == "mysql") {
                $db = new PDO("{$driver}:host={$dbhost};dbname={$dbname}", $dbuser, $dbpassword);
            } else {
                $db = new PDO("{$driver}:SERVER={$dbhost};DATABASE={$dbname}", $dbuser, $dbpassword);
            }
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }
    return $db;
}
Example #21
Show file File: ApiTest.php Project: rbertani/kanboard
0
 public static function setUpBeforeClass()
 {
     if (DB_DRIVER === 'sqlite') {
         @unlink(DB_FILENAME);
     } else {
         if (DB_DRIVER === 'mysql') {
             $pdo = new PDO('mysql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
             $pdo->exec('DROP DATABASE ' . DB_NAME);
             $pdo->exec('CREATE DATABASE ' . DB_NAME);
             $pdo = null;
         } else {
             if (DB_DRIVER === 'postgres') {
                 $pdo = new PDO('pgsql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
                 $pdo->exec('DROP DATABASE ' . DB_NAME);
                 $pdo->exec('CREATE DATABASE ' . DB_NAME . ' WITH OWNER ' . DB_USERNAME);
                 $pdo = null;
             }
         }
     }
     $service = new ServiceProvider\DatabaseProvider();
     $db = $service->getInstance();
     $db->table('settings')->eq('option', 'api_token')->update(array('value' => API_KEY));
     $db->table('settings')->eq('option', 'application_timezone')->update(array('value' => 'Europe/Paris'));
     $db->closeConnection();
 }
Example #22
Show file File: Usuario.php Project: ErickDomingues/projpdo2
0
 public function __construct(\PDO $db = null)
 {
     if ($db === null) {
         try {
             $db = new \PDO('mysql:host=localhost;dbname=pdo', 'root', 'root');
         } catch (\PDOException $e) {
             if ($e->getCode() === 1045) {
                 echo "Usuário incorreto";
             }
         }
     }
     $this->db = $db;
 }