Yii2 Create Database Connection - php

I want to create a database connection programmatically without using the config file. I have a form wherein the user enters the database details like the hostname, username, password and the database name. On the basis of these details a new test connection is made and if it passes it should generate the necessary files.
This is what I have tried:
// Create Test DB Connection
Yii::$app->set('id', [
'class' => 'yii\db\Connection',
'dsn' => $dsn,
'username' => $form->username,
'password' => $form->password,
'charset' => 'utf8'
]);
try {
// Check DB Connection
if (Yii::$app->db->getIsActive()) {
// Write Config
$config['components']['db']['class'] = 'yii\db\Connection';
$config['components']['db']['dsn'] = $dsn;
$config['components']['db']['username'] = $username;
$config['components']['db']['password'] = $password;
$config['components']['db']['charset'] = 'utf8';
Configuration::setConfig($config);
$success = TRUE;
return $this->redirect(['init']);
}else{
$errorMsg = 'Incorrect Configurations';
}
} catch (Exception $e) {
$errorMsg = $e->getMessage();
}
I have tested this again and again and even with correct configurations it is giving an error.
All the help is appreciated. Thanks in advance!

You can define a new connection this way:
$db = new yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
$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

I realised my mistake. When using Yii::$app->set() for setting up the db connection, you have to even manually open the connection using Yii::$app->db->open(). Yii doesn't open up the connection for you.

Related

how to set dynamic database values through classes and objects in php5

This is my code
<?php
class Connection
{
function __construct()
{
if(isset($_SERVER['SERVER_NAME']))
{
switch($_SERVER['SERVER_NAME'])
{
case 'www.hashstar.com':
$this->default = $this->dev;
break;
case 'www.hashstar.in':
$this->default = $this->prod;
break;
}
}
else
{
$this->default = $this->dev;
}
}
public $dev = array(
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'dbname',
);
public $prod = array(
'host' => 'localhost',
'login' => 'db_admin',
'password' => 'Admin#.2017',
'database' => 'db_main',
);
public function establish_connection()
{
$connection = new mysqli($this->host, $this->user, $this->pass, $this->db);
if($connection == TRUE)
{
return $connection;
}
else
{
die("Could Not Establish Connection! ".$connection->error);
}
}
}
?>
The problem with this code is that i have declared here varaibles 1st for offline and 2nd for online as i am using git i have to again and again change the codes before pushing to master branch. I even tried to use the .gitignore feature but it isn't working as well but still i wan to set the variables dynamically according to the server host.
I have tried using the switch case thing but its giving an syntactical error while compiling. Can anyone help mw with this code.
Any helps appreciated.
Set your database credentials in a new file that you will then add to .gitignore like so :
$dbConfig = array(
"host" => "localhost",
...
)
then simply access to your $dbConfig in your Connection class

PDO Connection not showing all errors

I'm having trouble getting errors to display with when making a new PDO connection. It only shows an error if I put the incorrect password in my config file. It won't show errors for an incorrect database name, username, or host.
<?php
// config file
return [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'query_test',
'username' => 'root',
'password' => '',
'options' => [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_CLASS,
PDO::ATTR_EMULATE_PREPARES => false
]
];
// connector file
use PDO;
class MySqlConnector implements ConnectorInterface
{
public function connect(array $config)
{
extract($config);
$dsn = "mysql:{$host};dbname={$database}";
$connection = new PDO($dsn, $username, $password, $options);
return $connection;
}
}
I've tried using try/catch blocks as well as setting ini display errors and error reporting E_ALL. Can't seem to figure this out.
Change:
$connection = new PDO($dsn, $username, $password, $options);
return $connection;
to:
try {
$connection = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
return $connection;
I overlooked a simple mistake. I had "mysql:{$host}" instead of "mysql:host={$host}".
Sorry for the silly mistake but thank you for your answer!

How can i send dynamic data in bootstrap file for Email in zend framework

I am sending email to user while registration. For that i am using Zend's default function.
For that i added code in my Bootstrap file.
protected function _initMail()
{
try {
$config = array(
'auth' => 'login',
'username' => 'username#gmail.com',
'password' => 'password',
'ssl' => 'tls',
'port' => 587
);
$mailTransport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
Zend_Mail::setDefaultTransport($mailTransport);
} catch (Zend_Exception $e){
}
}
Now my need is username,password and port i want to make this field dynamic. I want to fetch this record from the database. Can anyone please tell me how can i solve that problem. Any help will be appreciated.
I would say that you do not put these into the database. A better way would be to put them into a config file and then set them up from there. Doing a database call EVERY SINGLE time your application is called is not really optimal.
The way you should be doing it is:
protected function _initMail()
{
try {
$config = Zend_Controller_Front::getInstance()->getParam('bootstrap');
$config = $config->getOption("mail");
$mailTransport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
Zend_Mail::setDefaultTransport($mailTransport);
} catch (Zend_Exception $e){
}
}
That is assuming that your application.ini has this:
mail.auth="login"
mail.username="username#gmail.com"
mail.password="password"
mail.ssl="tls"
mail.port=587
However if you decide you want to do this, and have set up your database in the application.ini file (assuming you use ini files for config) something like this:
resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "your.database.host"
resources.db.params.dbname = "database_name"
resources.db.params.username = "username"
resources.db.params.password = "password"
resources.db.isDefaultTableAdapter = true
You can then do:
protected function _initMail()
{
$resource = $bootstrap->getPluginResource('db');
$db = $resource->getDbAdapter();
$select=$db->select()->from("emailSetup");
$credentials=$db->fetchOne($select);
[..email part here..]
}
P.S. I have not tested the select, but you should get the gist of it.

Zend LDAP authentication - How to setIdentity and getIdentity

I am using adldap library to authenticate users against Active Directory. Below is the piece of code I use to authenticate
$username = $_POST['username'];
$password = $_POST['password'];
require_once '/adlap/adLDAP.php';
try {
$adldap = new adLDAP();
}
catch (adLDAPException $e) {
echo $e;
exit();
}
$authUser = $adldap->user()->authenticate($username, $password);
How should I setIdentity for the user?
In Login system where we store username and password we can setIdentity as mentioned below
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
protected function _getAuthAdapter() {
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('users')
->setIdentityColumn('username')
->setCredentialColumn('password')
->setCredentialTreatment('SHA1(CONCAT(?,salt))');
return $authAdapter;
}
I am not storing password in Database and checking it directly against Active Directory. So I couldn't use the above solution.
How shall I setIdentity of users so that I can check if user hasIdentity() like this
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()){
}
I referred the following Stackoverflow question
Get display name for Zend LDAP Authentication.
However I am not sure how we shall "get('LDAP_host')" Zend Registry and how should we set it before. Below is the line of code I'm confused with
'host' => Zend_Registry::get('LDAP_host'),
Can someone please help me?
Zend_Registry::get('LDAP_host') simply returnes the hostname of your LDAP-Server. Somewhere before that line of code you will find a line similar to Zend_Registry::set('LDAP_host', 'ldap.example.com') which sets ldap.example.com as LDAP-server.
getAuthAdapter() in your case returns an instance of Zend_Auth_Adapter_DbTable but you want an instance of Zend_Auth_Adapter_Ldap. So you will have to either call a different method/function getLdapAuthAdapter() or rewrite the current method.
public function getLdapAuthAdapter() {
return new Zend_Auth_Adapter_Ldap(array(
'host' => 'ldap.example.com',
'accountDomainName' => 'example.com',
'accountDomainNameShort' => 'EXAMPLE',
'accountCanonicalForm' => 3,
'username' => "CN=user1,DC=example,DC=com",
'password' => 'pass1',
'baseDn' => "DC=example,DC=com",
'bindRequiresDn' => true,
));
}
$adapter = $this->getLdapAuthAdapter();
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
$result = $adapter->authenticate();
Hope that somehow helps.

PHP Laravel Framework Database Connection Error

I created a database called learning-laravel and I created a table which is users I want to get data from that table I wrote this code block:
Route::get('/',function()
{
$users = DB::table('users')->get();
return $users;
});
but I'm getting this type of error:
PDOException
SQLSTATE[HY000] [2005] Unknown MySQL server host 'localhost:3306' (2)
*/
public function createConnection($dsn, array $config, array $options)
{
$username = array_get($config, 'username');
$password = array_get($config, 'password');
return new PDO($dsn, $username, $password, $options);
}
Try instead of including the port in the host, add a "port" key and the port in a seperate key.
'host' => 'localhost',
'port' => '8889'
Looks like it may be trying to use that entire string as the host name.
As you said in your comment above, you have your MAMP settings pointing MySQL requests to port 3306. Here is the correct setting in that case:
'host' => 'localhost',
'port' => '3306'
Also, the "is it plugged in" suggestion would be to make sure your DB is actually running.
The solution is:
'host' => 'localhost:3306',

Categories