How to connect to a database without the config file in Yii2? - database

I am using, for the same problem, the code which is given in this question Yii2 Create Database Connection.
I realise the $config variable is no longer the one in the web.php file, from the "config" folder, and that he is changing $configin his Configuration::setConfig() function.
My question for those more experienced than me in Yii is what should I write
in the web.php file in the db field (or in the db.php file) to "create a database connection programmatically without using the config file" ?
in the function Configuration::setConfig() to properly configure the application?
I'm sorry if my question is not clear enough. Please ask for details in the comments if needed. Thank you!

You can define a new connection this way
$db = new yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]); and
$db->open();
After the DB connection is established, one can execute SQL statements
like the following eg: :
$command = $db->createCommand('SELECT * FROM post');
$posts = $command->queryAll(); or
$command = $connection->createCommand('UPDATE post SET status=1');
$command->execute();
you can look at this for doc and guide
http://www.yiiframework.com/doc-2.0/guide-db-dao.html
http://www.yiiframework.com/doc-2.0/yii-db-connection.html

Related

Codeigniter 3 - override db hostname in model

I'm using a small CI codebase to run a simple feature in a larger codebase (a mix of Zend and Syfmony).
That master system uses a bootstrap file to set various global variables that I've accessed by creating a library file. it all works great and I can access the parent system, functions and global vars within my CI app.
BUT... That parent system stores DB connection info in sever related override files (So if code is deployed on server test.server, then config file test.server is loaded, and all relevant vars are set to that server.
What I need to do is tell my DB config file to access those vars.
OR, in my model, set hostname, user and pass vars.
I've tried:
$this->db->hostname = GLOBAL_VAR_HOSTNAME;
but that is not working.
So can I pass any data from my library file into a config file, so I can set:
$db['default'] = array(
'hostname' => GLOBAL_VAR_HOSTNAME,
'username' => GLOBAL_VAR_USERNAME,
etc etc
Setting up all the DB info in the standard database config file as new servers are added all the time and they tech leads want to use the existing system for sharing vars.
I'm going for a coffee...
You can setup manual connections like this:
$this->load->database(array(
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'ci',
'dbdriver' => 'mysqli',
));
var_dump($this->db->get('posts')->result());
Or you can create another connection completly:
$database = $this->load->database(array(
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'mydb',
'dbdriver' => 'mysqli',
), TRUE);
var_dump($database->get('posts')->result());

Setting Environment-specific database in CakePHP

I am using CakePHP and was trying to implement https://github.com/josegonzalez/cakephp-environments
Which seemed to be going fine except that I have no idea where to specify the env specific database info.
Does anyone know where to set these?
I personally haven't used the plugin, however from looking at the code and the docs, if you were using the suggested database configuration, then it seems that you would define the options as either environment variables, which can be done in various ways, for example
in your server configuration (Apache example)
in your cloud varibale settings (Heroku example)
manually using putenv(), $_ENV, $_SERVER
$name = 'MYSQL_DB_HOST';
$value = 'localhost';
putenv("$name=$value");
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
...
or as CakePHP configuration values via the Environment::configure() calls, something like:
Environment::configure('development',
true,
array(
'MYSQL_DB_HOST' => 'localhost',
'MYSQL_USERNAME' => 'user',
// ...
),
// ...
);

How to use Zend Framework 2 with MS SQL Server on *nix?

What, if it exists, is the canonical way to use ZF2 with MS SQL Server on a non-Windows OS?
From what I can tell from the documentation, only the Sqlsrv driver is officially supported, which only works on the Windows platform.
In ZF1, we used the Pdo_Mssql adapter and specified the pdoType as dblib. I can't find any references to doing anything similar in ZF2.
Apparently there was a Pdo\Mssql driver some time ago which was removed during a major refactoring, but I don't see a currently documented way of using Pdo_Dblib.
According to the adapter documentation above, you can set the driver in the adapter config to Pdo=OtherPdoDriver, but there's no documented examples of this usage. Does that mean you can use Pdo=Pdo_Dblib or Pdo=dblib and it will work automagically?
I've found passing references to a PDO ODBC driver, which would be a usable alternative, but can't find any documentation or code references.
Install the php5-sybase. Make sure that freetds is installed. You should have a conf file under /etc/freetds called freetds.conf.
In your freetds.conf file you should setup your mssql connection like this:
[MyMsSqlServer]
host = symachine.domain.com
port = 5000
tds version = 5.0
Then, (using the ZF2 Albums Tutorial as an example here) you set up the adapter like this:
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'dblib:host=MyMsSqlServer;dbname=zf2tutorial',
'charset' => 'UTF-8',
'username' => 'username',
'password' => 'password',
'pdotype' => 'dblib',
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
See if this gets you anywhere and let me know. I had a bitch of a time getting this to work, and I am more then happy to help anyone else that is having issues with this!!!
You can use a pdo connection with pdotype set to dblib (with loaded pdo_dblib extension).
sqlsrv is only available for Windows.
Here you can see how freetds and unixodbc is configured to connect to a MS SQL Server.
http://featurebug.blogspot.de/2011/01/mac-os-x-php-zend-server-ce-freetds-and.html
UPDATE:
Here is an example how to use a connection string to connect:
$db = new Zend\Db\Adapter\Adapter(
array(
'driver' => 'Pdo',
'dsn' => 'dblib:host=mssql_freetds;',
'username' => 'mssql_username',
'password' => 'mssql_password',
)
);
Yes, you can use odbc to connect. It is not currently officially supported, but you can get it working fairly easily, with minimal modifications.
The first thing you need to do, is make sure you can connect using the basic PHP PDO functions. So, do something like this:
$resource = new PDO('odbc:driver=FreeTDS;dbname=MYDB;Server=127.0.0.1;Port=8090;UID=Testuser;PWD=testpass;', 'Testuser', 'testpass', array());
$s = $resource->prepare('SELECT * FROM TEST_TABLE');
$r=$s->execute();
var_dump($r);
You'll need to change the host, port, user, pass, table name etc. for your settings, but you can use this to make sure you have those details right. Once you know what you are doing to connect, you can access it with Zend, like this:
$configArray = array(
'driver' => 'pdo_odbc',
'driver_options' => array('driver' => 'FreeTDS'),
'platform' => 'Mssql',
'dbname' => 'MYDB',
'host' => '127.0.0.1',
'port' => 8090,
'user' => 'Testuser',
'pass' => 'testpass'
);
$adapter = new Zend\Db\Adapter\Adapter($configArray);
$q = new Zend\Db\Sql\Select();
$q->from('TEST_TABLE');
$sql = $q->getSqlString($adapter->platform);
$r = $adapter->query($sql);
echo $r->getSql()."\n";
$result = $r->execute();
while(($res = $result->next()) !== false){
print_r($res);
}
However this will not actually work, for two reasons. First, the platform - Zend currently doesn't have an mssql platform; it defaults to sql92, which will not work, because it quotes identifiers in "", when mssql needs them to be quoted with []. So you'll need to copy the Zend/Db/Adapter/Platform/Sql92.php as Mssql.php, and change it to use [ and ] instead of ".
Second, because the dsn for connection to odbc requires the driver field, which zend currently doesn't support. You'll need to open up the Driver/Pdo/Connection class and modify the connect function, to add $dsn[] = "driver={$options['driver']}"; and replace $dsn[] = "host={$hostname}"; with $dsn[] = "server={$hostname}"; when $pdoDriver = odbc.
Note that the other answers are posted by people who do not actually understand how the Zend 2 library works - if you specify a value for 'dsn', then the other fields are ignored. I have NO idea where they got the idea of 'pdotype', as that is not a field that appears anywhere in the code.

ZF2 - Record not existing

I try to use the zf2 db validator to check if a record does not exist.
I set the follow code in my controller:
$validator = new NoRecordExists(
array(
'table' => 'topics',
'field' => 'topic',
)
);
after this configuration I try to validate but I got 'an error occurred', can't find any other error output who can tell me more about this error.
var_dump($validator->isValid('test'));
If someone can give me some tips, would be great :)
thx
Have you set the DB Adapter?
You can pass it in the contructor or called setAdapter();
validator->setAdapter(
$this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')
);
You could set this up in your service config to automatically inject the adapter for you.

Codeigniter PDO integration

i did lot of research on the web but i didnt find anything that could help me to use PDO in codeigniter. I saw in the change lof of CI 2.1.0(i think) that pdo driver was added to the framwork.
I ended up now with a database.php config file that looks like this:
$db['default']['hostname'] = 'mysql:host=myhostname;port=myport';
$db['default']['username'] = 'myusername';
$db['default']['password'] = 'mypassword';
$db['default']['database'] = 'mydb';
$db['default']['dbdriver'] = 'pdo';
So now(after a lot of wasted time to get the snippet above to work -.- ) i receive no error about connection, but HOW TO EXECUTE QUERY NOW? i cant figure out what syntax will work and how to build queries. Anyone have hints?
PS: if you're wordering about why i need pdo in ci, the answer is my boss want me to create a structured enviroment with:
CI 2.x + (done)
Smarty 3 (done)
PhpUnit (not yet)
PDO (not yet)
so if you have also any hints for integrate phpunit feels free to answer. Ty in advance
You use PDO the same way you use any other database driver in CodeIgniter. If you are still unsure then I would recommend reading the documentation on the Database Class.
You can issue standard queries by explicitly writing the query or you can use the Active Record Class (which is more of a query builder).
Here are some examples:
// Standard query
$results = $this->db->query('SELECT name, title, email FROM my_table');
// Active record
$this->db->select('name, title, email');
$results = $this->db->get('my_table');
As for integrating PHPUnit, have a look at https://github.com/cmillr/CI-PHPUnit (I haven't tested it myself) or look around the CodeIgniter forums. I've seen a ton of topics on integrating PHPUnit with CodeIgniter.
You need to change your config a little:
'dsn' => 'mysql:host=localhost;dbname=codeigniter',
//'hostname' => 'localhost',
'username' => 'codeigniter',
'password' => 'codeigniter',
'database' => 'codeigniter',
Notice we use dsn, not hostname.
After that, simply use your $this->db-> like you always do - the PDO driver will translate everything to PDO methods
A little dated, but the topic is lacking clear explanations & docs so I wrote this - hope it helps clarify for people:
http://codebyjeff.com/blog/2013/03/codeigniter-with-pdo

Resources