PHP PDO Examples

PHP PDO - 30 examples found. These are the top rated real world PHP examples of PDO extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
 /**
  * Returns a PDOStatement
  *
  * This method will return the same object for equal queries.
  *
  * @param string $sql
  * @return \PDOStatement
  * @throws \PDOException
  */
 public function prepare($sql)
 {
     if (!array_key_exists($sql, $this->statements)) {
         $this->statements[$sql] = $this->pdo->prepare($sql);
     }
     return $this->statements[$sql];
 }
Example #2
0
 public function testEquipmentUpdate()
 {
     $this->delete($this->insert(array(Object::TIME_IN_SECONDS => 3600, Object::DISTANCE => 12, Object::SHOEID => 1)));
     $this->delete($this->insert(array(Object::TIME_IN_SECONDS => 3600, Object::DISTANCE => 12, Object::SHOEID => 2)));
     $this->assertEquals(array('km' => 10, 'time' => 3000), $this->PDO->query('SELECT `km`, `time` FROM `' . PREFIX . 'shoe` WHERE `id`=1 AND `accountid`=0')->fetch(PDO::FETCH_ASSOC));
     $this->assertEquals(array('km' => 0, 'time' => 0), $this->PDO->query('SELECT `km`, `time` FROM `' . PREFIX . 'shoe` WHERE `id`=2 AND `accountid`=0')->fetch(PDO::FETCH_ASSOC));
 }
Example #3
0
 public function setUp(PDO $pdo, $sql)
 {
     $sql = explode(';', trim($sql));
     foreach ($sql as $query) {
         $pdo->exec(trim($query));
     }
 }
Example #4
0
 public static function getMysqlConnexion()
 {
     $db = new \PDO('mysql:host=192.168.220.11;dbname=news', 'root', 'greg');
     # $db = new \PDO('mysql:host=192.168.2.1;dbname=news', 'root', 'root');
     $db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
     return $db;
 }
Example #5
0
 public static function updateImage($id, $img)
 {
     $sql = "UPDATE yy_article SET img = '{$img}' WHERE id = {$id}";
     $config = self::getDb()->getConfig();
     $pdo = new PDO("mysql:host={$config['host']};dbname={$config['dbname']}", $config['username'], $config['password']);
     return $pdo->exec($sql);
 }
Example #6
0
 /**
  * 根据读写性要求设置一个适合的pdo对象
  * 
  * @param $rw 服务器的读写性
  * @return object
  */
 public function getConnection($rw = 'rw')
 {
     $params = $this->_params;
     //如果是只读查询,从所有服务器中随机挑选一台
     if ($rw == 'r') {
         $rw = 'all';
     }
     if (isset($this->_pdos[$rw]) && $this->_pdos[$rw] instanceof PDO) {
         $this->_pdo = $this->_pdos[$rw];
         return $this->_pdo;
     }
     //随机从满足读写性要求的服务器中挑选出一台服务器
     $index = rand(0, sizeof($params[$rw]) - 1);
     $params = $params[$rw][$index];
     if (!isset($params['port'])) {
         $params['port'] = '3306';
     }
     $dsn = "mysql:host={$params['host']};port={$params['port']};dbname={$params['dbname']}";
     $pdo = new PDO($dsn, $params['username'], $params['password']);
     if ($params['persistent']) {
         $pdo->setAttribute(PDO::ATTR_PERSISTENT, true);
     }
     $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $pdo->exec("SET NAMES {$params['charset']}");
     $this->_pdo = $pdo;
     $this->_pdos[$rw] = $pdo;
     return $this->_pdo;
 }
/**
 * To use this theme, you need to set up a database "wp_example" with a table called "wp_posts" (Whata Primitive Posts)
 * and give it a column 'post_title'
 */
function wp_theme_display_theme()
{
    $hostname = 'localhost';
    $user = 'username';
    $pass = 'password';
    $database = 'wp_example';
    $db_connection = new PDO("mysql:host=" . $hostname . ";dbname=" . $database, $user, $pass);
    $results = $db_connection->query('SELECT post_title FROM wp_posts WHERE 1 ORDER by rand() LIMIT 1');
    $post_title = $results[0]['post_title'];
    ?>
	<!doctype html>
	<html>
	    <head>
	        <title>WP CMS</title>
	        <link rel="stylesheet" href="style.css">
	    </head>
	    <body>
	        <h1><?php 
    echo $post_title;
    ?>
</h1>
	    </body>
	</html>

	<?php 
}
Example #8
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('/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'))->getMock();
 }
Example #9
0
function cs_sql_connect($cs_db, $test = 0)
{
    $error = '';
    if (!extension_loaded('pdo') or !extension_loaded('pdo_mysql')) {
        $error = 'PHP extensions pdo and pdo_mysql must be activated!';
    } else {
        $param = empty($cs_db['place']) ? '' : 'host=' . $cs_db['place'] . ';';
        $param .= 'dbname=' . $cs_db['name'];
        try {
            $connect = new PDO('mysql:' . $param, $cs_db['user'], $cs_db['pwd']);
        } catch (PDOException $err) {
            $error = $err->getMessage();
        }
    }
    global $cs_main;
    $sql_charset = strtolower($cs_main['charset']);
    if (empty($error) and $sql_charset == 'utf-8') {
        $connect->exec("SET NAMES 'utf8'");
    }
    if (empty($test) and empty($error)) {
        return $connect;
    } elseif (empty($test)) {
        cs_error_sql(__FILE__, 'cs_sql_connect', $error, 1);
    } else {
        return $error;
    }
}
Example #10
0
 public function __construct()
 {
     //J'initialise quelques variables.
     if ($this->table === false) {
         $this->table = strtolower(get_class($this)) . 's';
     }
     // Je me connecte à la base.
     $conf = Conf::$database[$this->conf];
     if (isset(Model::$connection[$this->conf])) {
         $this->db = Model::$connection[$this->conf];
         return true;
     }
     try {
         $pdo = new PDO('mysql:host=' . $conf['host'] . ';dbname=' . $conf['database'] . ';', $conf['login'], $conf['password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
         $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
         Model::$connection[$this->conf] = $pdo;
         $this->db = $pdo;
     } catch (PDOException $e) {
         if (Conf::$debug >= 1) {
             die($e->getMessage());
         } else {
             die('Impossible de se connecter à la base de donnée.');
         }
     }
 }
function getDatabase()
{
    $config = array('DB_DNS' => 'mysql:host=localhost;port=3306;dbname=phpclasssummer2015', 'DB_USER' => 'root', 'DB_PASSWORD' => '');
    $db = new PDO($config['DB_DNS'], $config['DB_USER'], $config['DB_PASSWORD']);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    return $db;
}
Example #12
0
 /**
  * 连接数据库
  * 
  */
 private function getdb_content()
 {
     $db = new PDO($this->dsn_content, $this->dbuser_content, $this->dbpasswd_content);
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $db->exec('set names utf8');
     return $db;
 }
Example #13
0
 public function connectDB()
 {
     try {
         $db_host = 'localhost';
         //  hostname
         $db_name = 'matheno_mygig';
         //  databasename
         $db_user = 'matheno_marijke';
         //  username
         $user_pw = 'Gabruko3';
         //  password
         $con = new PDO('mysql:host=' . $db_host . '; dbname=' . $db_name, $db_user, $user_pw);
         $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         $con->exec("SET CHARACTER SET utf8");
         //  return all sql requests as UTF-8
         return $con;
     } catch (PDOException $err) {
         echo "harmless error message if the connection fails";
         $err->getMessage() . "<br/>";
         file_put_contents('PDOErrors.txt', $err, FILE_APPEND);
         // write some details to an error-log outside public_html
         die;
         //  terminate connection
     }
 }
Example #14
0
        function authenticate($username, $password) {
    
             $db = new PDO('mysql:dbname=dwa;host=localhost;charset=utf8', 'dbuser', '123');
                $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            try {
               
                $stmt = $db->prepare("SELECT zaporka FROM korisnik WHERE korIme = :username");
                $stmt->bindParam(':username', $username);
                $stmt->execute();

                $result = $stmt->fetch(PDO::FETCH_ASSOC);

                $hash = $result['zaporka'];

                if(!password_verify($password, $hash)) {    
            
                    return false;
                }

                $stmt = $db->prepare("SELECT id, korIme, ime FROM korisnik WHERE korIme = :username");
                $stmt->bindParam(':username', $username);
                $stmt->execute();

                $user = $stmt->fetch();

                $_SESSION['user'] = $user['korIme'];
                return true;

            } catch(PDOException $ex) {
                echo "Nes ne valja: ".$ex->getMessage();
                return false;
            }
    }
Example #15
0
function getUserData($username)
{
    try {
        $userarray = array();
        #echo "username: $username<br/>";
        $db = new PDO('mysql:dbname=michaeq6_mheartsj', 'michaeq6_mj', 'mj060708');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $db->prepare("SELECT group_id FROM users WHERE name=?");
        $stmt->bindParam(1, $username);
        $completed = $stmt->execute();
        $array = $stmt->fetch(PDO::FETCH_BOTH);
        #echo "group id: " . $array['group_id'] . "<br/>";
        $userarray['gid'] = $array['group_id'];
        $stmt = $db->prepare("SELECT password FROM groups WHERE id=?");
        $stmt->bindParam(1, $array['group_id']);
        $completed = $stmt->execute();
        $array = $stmt->fetch(PDO::FETCH_BOTH);
        #echo "password: " . $array['password'] . "<br/>";
        $userarray['password'] = $array['password'];
        #return $array['password'];
        return $userarray;
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
    return false;
}
Example #16
0
 /**
  * Provides Mutex factories.
  *
  * @return callable[][] The mutex factories.
  */
 public function provideMutexFactories()
 {
     $cases = ["NoMutex" => [function () {
         return new NoMutex();
     }], "TransactionalMutex" => [function () {
         $pdo = new \PDO("sqlite::memory:");
         $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
         return new TransactionalMutex($pdo);
     }], "FlockMutex" => [function () {
         vfsStream::setup("test");
         return new FlockMutex(fopen(vfsStream::url("test/lock"), "w"));
     }], "SemaphoreMutex" => [function () {
         return new SemaphoreMutex(sem_get(ftok(__FILE__, "a")));
     }], "SpinlockMutex" => [function () {
         $mock = $this->getMockForAbstractClass(SpinlockMutex::class, ["test"]);
         $mock->expects($this->any())->method("acquire")->willReturn(true);
         $mock->expects($this->any())->method("release")->willReturn(true);
         return $mock;
     }], "LockMutex" => [function () {
         $mock = $this->getMockForAbstractClass(LockMutex::class);
         $mock->expects($this->any())->method("lock")->willReturn(true);
         $mock->expects($this->any())->method("unlock")->willReturn(true);
         return $mock;
     }]];
     if (getenv("MEMCACHE_HOST")) {
         $cases["MemcacheMutex"] = [function () {
             $memcache = new Memcache();
             $memcache->connect(getenv("MEMCACHE_HOST"));
             return new MemcacheMutex("test", $memcache);
         }];
         $cases["MemcachedMutex"] = [function () {
             $memcache = new Memcached();
             $memcache->addServer(getenv("MEMCACHE_HOST"), 11211);
             return new MemcachedMutex("test", $memcache);
         }];
     }
     if (getenv("REDIS_URIS")) {
         $uris = explode(",", getenv("REDIS_URIS"));
         $cases["PredisMutex"] = [function () use($uris) {
             $clients = array_map(function ($uri) {
                 return new Client($uri);
             }, $uris);
             return new PredisMutex($clients, "test");
         }];
         $cases["PHPRedisMutex"] = [function () use($uris) {
             $apis = array_map(function ($uri) {
                 $redis = new Redis();
                 $uri = parse_url($uri);
                 if (!empty($uri["port"])) {
                     $redis->connect($uri["host"], $uri["port"]);
                 } else {
                     $redis->connect($uri["host"]);
                 }
                 return $redis;
             }, $uris);
             return new PHPRedisMutex($apis, "test");
         }];
     }
     return $cases;
 }
Example #17
0
 public static function validateTeam(\PDO $pdo_db, $name = null, $desc = null, $creator = null) : bool
 {
     $name = trim($name);
     $desc = trim($desc);
     $creator = (int) $creator;
     if ($name === null || empty($name) || $desc === null || empty($desc) || $creator === null || empty($creator)) {
         return (bool) false;
     }
     $res_new = preg_match('/[^A-Za-z0-9\\_\\s\\-\\.\']+/', $name, $matches);
     if ($res_new != 0) {
         return (bool) false;
     }
     $res_new2 = preg_match('/[^A-Za-z0-9\\_\\s\\-\\.\']+/', $desc, $matches);
     if ($res_new2 != 0) {
         return (bool) false;
     }
     // Just a test to see if an team with a name of $name exists.
     // This is just a temp fix until we find a better one.
     $sql = "SELECT COUNT(*) as found FROM ::prefix::teams WHERE team_name=:team_name AND creator <>:creator";
     $stmt = $pdo_db->prepare($sql);
     $stmt->bindParam(':team_name', $name);
     $stmt->bindParam(':creator', $creator);
     $stmt->execute();
     $num_res = $stmt->fetch(\PDO::FETCH_ASSOC);
     $returnvalue = !($num_res['found'] > 0);
     return (bool) $returnvalue;
 }
Example #18
0
function checkpass()
{
    $dbHost = getenv('OPENSHIFT_MYSQL_DB_HOST');
    //Get host from OpenShift
    $dbPort = getenv('OPENSHIFT_MYSQL_DB_PORT');
    //Get Port from OpenShift
    $dbUser = getenv('OPENSHIFT_MYSQL_DB_USERNAME');
    //Get UserName from OpenShift
    $dbPassword = getenv('OPENSHIFT_MYSQL_DB_PASSWORD');
    //Get Password from OpenShift
    $dbName = "users";
    try {
        $db = new PDO("mysql:host={$dbHost}:{$dbPort};dbname={$dbName}", $dbUser, $dbPassword);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * from users where name='{$_POST['userlogin']}' and password='{$_POST['password']}'";
        $result = mysql_query($sql, $conn) or die(mysql_error());
        return mysql_num_rows($result);
    } catch (Exception $ex) {
        // Please be aware that you don't want to output the Exception message in
        // a production environment
        echo "Error with DB. Details: {$ex}";
        die;
    }
    function print_secure_content()
    {
        echo "<b><h1>hi mr.{$_SESSION['user']}</h1>";
        echo "<br><h2>only a logged in user can see this</h2><br><a href='logout.php'>Logout</a><br>";
    }
}
 public static function connect($a)
 {
     $db1 = new PDO('sqlite:' . $a['dbname']);
     # this should be a passable option
     $db1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     return $db1;
 }
Example #20
0
 public function connect($name, $params)
 {
     $params = array_merge(array('dsn' => null, 'user' => '', 'password' => '', 'options' => array()), $params);
     $con = new PDO($params['dsn'], $params['user'], $params['password'], $params['options']);
     $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $this->connections[$name] = $con;
 }
Example #21
0
 function __construct() {
     $f3 = Base::instance();
     $dbh = new PDO($f3->get('db_dns') . $f3->get('db_name'), $f3->get('db_user'), $f3->get('db_pass'));
     $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $this->f3 = $f3;
     $this->db = $dbh;
 }
 protected function existRow($query)
 {
     $statement = self::$dbh->prepare($query);
     $statement->execute();
     $result = $statement->fetchAll();
     return isset($result[0]['cnt']) && 1 === (int) $result[0]['cnt'];
 }
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     $config = $serviceLocator->get('config');
     try {
         $pdo = $pdo = new \PDO($config['dbAdapterPostgre']['dsn'], $config['dbAdapterPostgre']['username'], $config['dbAdapterPostgre']['password']);
         $sql = "          \n            SELECT                \n                REPLACE(TRIM(SUBSTRING(crypt(sf_private_key_value,gen_salt('xdes')),6,20)),'/','*') AS public_key\n                FROM info_users a \n                INNER JOIN sys_acl_roles sar ON sar.id = a.role_id AND sar.active=0 AND sar.deleted=0 \n                WHERE a.username = :username \n                    AND a.password = :password   \n                    AND a.deleted = 0 \n                    AND a.active = 0 \n                    Limit 1 \n                \n                                 ";
         $statement = $pdo->prepare($sql);
         $statement->bindValue(':username', $_POST['eposta'], \PDO::PARAM_STR);
         $statement->bindValue(':password', md5($_POST['sifre']), \PDO::PARAM_STR);
         //echo debugPDO($sql, $parameters);
         $statement->execute();
         $result = $statement->fetchAll(\PDO::FETCH_ASSOC);
         $publicKey = true;
         if (isset($result[0]['public_key'])) {
             $publicKey = $result[0]['public_key'];
         }
         $errorInfo = $statement->errorInfo();
         if ($errorInfo[0] != "00000" && $errorInfo[1] != NULL && $errorInfo[2] != NULL) {
             throw new \PDOException($errorInfo[0]);
         }
         //return array("found" => true, "errorInfo" => $errorInfo, "resultSet" => $result);
         return $publicKey;
     } catch (\PDOException $e) {
         $pdo->rollback();
         return array("found" => false, "errorInfo" => $e->getMessage());
     }
     //return false;
 }
function autocomplete_log()
{
    try {
        $conn = new PDO("mysql:host=localhost;dbname=csv", 'root', 'root', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql_select = "SELECT ID_Appli, Nom, Basicat FROM ftcarto";
        $stmt0 = $conn->prepare($sql_select);
        $stmt0->execute();
        $result0 = $stmt0->fetchAll();
        $log = array();
        foreach ($result0 as $row) {
            array_push($log, $row['ID_Appli'], $row['Nom'], $row['Basicat']);
        }
        array_unique($log);
        /*for($i=0;$i<count($log);$i++){
              if($log[$i]==''){
                  unset($log[$i]);
              }
          }*/
        array_values($log);
    } catch (PDOException $e) {
        echo '<br/>' . $e->getMessage() . '<br/>';
    }
    $conn = null;
    $tst = array("A1", "A2", "B");
    header('Content-Type: application/json');
    echo json_encode($log);
}
Example #25
0
 public function check()
 {
     if (phpversion() < '5.0.0') {
         return Response::json(FAIL, array('您的php版本过低,不能安装本软件,请升级到5.0.0或更高版本再安装,谢谢!'));
     }
     if (!extension_loaded('PDO')) {
         return Response::json(FAIL, array('请加载PHP的PDO模块,谢谢!'));
     }
     if (!function_exists('session_start')) {
         return Response::json(FAIL, array('请开启session,谢谢!'));
     }
     if (!is_writable(ROOT_PATH)) {
         return Response::json(FAIL, array('请保证代码目录有写权限,谢谢!'));
     }
     $config = (require CONFIG_PATH . 'mysql.php');
     try {
         $mysql = new PDO('mysql:host=' . $config['master']['host'] . ';port=' . $config['master']['port'], $config['master']['user'], $config['master']['pwd']);
     } catch (Exception $e) {
         return Response::json(FAIL, array('请正确输入信息连接mysql,保证启动mysql,谢谢!'));
     }
     $mysql->exec('CREATE DATABASE ' . $config['master']['dbname']);
     $mysql = null;
     unset($config);
     return Response::json(SUCC, array('检测通过'));
 }
Example #26
0
 public static function listAvailable(\PDO $pdo_db, string $lang) : array
 {
     // Get a list of supported languages
     $sql = "SELECT section, name, value FROM ::prefix::languages WHERE category = :category AND (name = :name1 OR name = :name2) ORDER BY section, name;";
     $stmt = $pdo_db->prepare($sql);
     $stmt->bindValue(':category', 'regional');
     $stmt->bindValue(':name1', 'local_lang_name');
     $stmt->bindValue(':name2', 'local_lang_flag');
     $stmt->execute();
     $lang_rs = $stmt->fetchAll();
     $list_of_langs = array();
     if (is_array($lang_rs) === true && count($lang_rs) >= 2) {
         foreach ($lang_rs as $langinfo) {
             if (array_key_exists($langinfo['section'], $list_of_langs) === false) {
                 $list_of_langs[$langinfo['section']] = array();
             }
             switch ($langinfo['name']) {
                 case 'local_lang_flag':
                     $list_of_langs[$langinfo['section']] = array_merge($list_of_langs[$langinfo['section']], array('flag' => $langinfo['value']));
                     break;
                 case 'local_lang_name':
                     $list_of_langs[$langinfo['section']] = array_merge($list_of_langs[$langinfo['section']], array('lang_name' => $langinfo['value']));
                     break;
             }
         }
         // Extract our default language, and remove it from the list of supported languages.
         $our_lang = $list_of_langs[$lang];
         unset($list_of_langs[$lang]);
         // Add our default language back in, this should be put at the end of the list.
         $list_of_langs[$lang] = $our_lang;
         unset($our_lang);
     }
     // Return the list of installed languages
     return $list_of_langs;
 }
 public function actionIndex()
 {
     if (isset($_GET['id'])) {
         $model = Document::model()->findByPk($_GET['id']);
         $this->render('detail', array('model' => $model));
         $cfg = (require dirname(__FILE__) . '/../../config/main.php');
         //print '<pre>';
         //print_r($cfg['components']['db']);
         if (preg_match("/^mysql:host=(\\w.*);dbname=(\\w.*)/i", $cfg['components']['db']['connectionString'], $match)) {
             //print_r($match);
         }
         //$db_name = "myphotos";
         //$db_server = "localhost";
         //$db_user = "root";
         //$db_pass = "";
         $db_name = $match[2];
         $db_server = $match[1];
         $db_user = $cfg['components']['db']["username"];
         $db_pass = $cfg['components']['db']["password"];
         $sql = "UPDATE gs_document SET counter=counter+1 WHERE doc_id='" . $_GET['id'] . "'";
         //print $sql;
         //$command = Yii::app()->db->createCommand($sql);
         //$command->execute();
         $dbh = new PDO('mysql:host=' . $db_server . ';port=3306;dbname=' . $db_name, $db_user, $db_pass, array(PDO::ATTR_PERSISTENT => false));
         $stmt = $dbh->prepare($sql);
         $stmt->execute();
     } else {
         $criteria = new CDbCriteria();
         $criteria->select = '*';
         $criteria->condition = 'status = 1';
         $criteria->order = 'sort_order ASC ,last_update DESC';
         $model = Document::model()->findAll($criteria);
         $this->render('index', array('model' => $model));
     }
 }
Example #28
0
function kapcsolat()
{
    // phpmyadminban rft néven kell megcsinálni az adatbázist vagy át kell irni az rftt
    $kapcsolat = new PDO('mysql:dbname=rft;host=localhost', 'root', '');
    $kapcsolat->exec("set names utf8");
    return $kapcsolat;
}
Example #29
0
 public function getData()
 {
     try {
         $bdd = new PDO('mysql:host=localhost; dbname=meteo', 'root', '');
         $bdd->exec("SET NAMES 'UTF8'");
     } catch (Exception $e) {
         throw 'Erreur : ' . $e->getMessage();
     }
     $dataRead = $bdd->query('SELECT DATE_FORMAT(date,"%d-%m-%Y") AS date, city, period, resume, idWeather, tptMin, tptMax, comment FROM forecast WHERE date > "2015-08-10" LIMIT 6');
     $numberRow = $dataRead->rowCount();
     if ($numberRow > 0) {
         $i = 1;
         while ($display = $dataRead->fetch()) {
             $forecast[$i]['date'] = $display['date'];
             $forecast[$i]['city'] = $display['city'];
             $forecast[$i]['period'] = $display['period'];
             $forecast[$i]['resume'] = $display['resume'];
             $forecast[$i]['idWeather'] = $display['idWeather'];
             $forecast[$i]['tptMin'] = $display['tptMin'];
             $forecast[$i]['tptMax'] = $display['tptMax'];
             $forecast[$i]['comment'] = $display['comment'];
             $i++;
         }
         $dataRead->closeCursor();
         return $forecast;
     } else {
         return 'Pas de données';
     }
 }
Example #30
0
 public function getById($id)
 {
     if (is_int($id)) {
         $siglatempo = null;
         $stm = $this->pdo->prepare('SELECT
                 id,
                 sigla,
                 descricao
             FROM
                 siglatempo
             WHERE
                 id = :id;');
         $stm->setFetchMode(PDO::FETCH_CLASS, 'PrevisaoTempo\\DataAccess\\Entity\\SiglaTempo');
         $stm->bindValue(':id', $id, PDO::PARAM_INT);
         if ($stm->execute()) {
             $siglatempo = $stm->fetch();
             $stm->closeCursor();
         }
         if (!$siglatempo instanceof SiglaTempo) {
             throw new \RuntimeException('Falha ao recuparar siglatempo');
         }
         return $siglatempo;
     }
     throw new \InvalidArgumentException(print_r($id, true) . ' e um valor invalido');
 }