Check if Credentials for Database are valid with Laravel - mysql

I'm writing a small tool for which it is necessery to check if database-credentials are valid and working. The tool is based on laravel. The credentials are submitted via a post-route.
$mysql2 = array(
'driver' => 'mysql',
'host' => 'localhosts',
'database' => 'test',
'username' => 'testUser',
'password' => 'testPasswort',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
);
DB::connection($mysql2);
I hoped I could do something like this code above. But I can't get it working. Has anyone ever attempted something similar?
Edit1:
I tried switching the credentials in the config file:
Config::set("database.connections.mysql", [
"host" => "localhast",
"database" => "test",
"username" => "testUser",
"password" => "testPasswort"
]);
$con = DB::connection()->getPdo();
Sadly there is still some error thrown.

Have you tried using a new connection (not editing the already existing one)
$newName = uniqid('db'); //example of unique name
Config::set("database.connections.".$newName, [
"host" => "localhast",
"database" => "test",
"username" => "testUser",
"password" => "testPasswort"
]);
try {
DB::connection($newName)->getPdo();
} catch (\Exception $e) {
//handle error
}

You don't need to pass the array to check DB connection just simply apply this code you will get to know about connection. This will automatically take the .env file connection variables.
try {
DB::connection()->getPdo();
} catch (\Exception $e) {
die("Could not connect to the database. Please check your configuration. error:" . $e );
}

Related

I cannot create new tables for migration

I am running
./yii migrate/create create_junction_table_for_sales_and_branch_tables --fields="created_at:dateTime"
and I get the following error:
Error: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known.
Trying to create an ordinary table also gives the same error. I cannot solve this issue.
This is part of my code in common/config/main.php:
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=' . getenv('DB_HOST') . ';port='.
getenv('DB_PORT', 3306) .';dbname=' . getenv('DB_NAME'),
'username' => getenv('DB_USERNAME'),
'password' => getenv('DB_PASSWORD'),
'charset' => 'utf8',
],
The best way to configure your db connection is:
return [
'class' => \yii\db\Connection::class,
'dsn' => 'mysql:host=address:port;dbname=mydatabase',
'username' => 'admin',
'password' => '123321',
'charset' => 'utf8',
];
Also you can define variables in yor cfg file, and use them, don't forget, that env.variables, which you are using, must be defined in your environment
// You may define env.variable in your system.
$host = 'localhost';
$port = '3306';
$dbname = 'mydatabase';
$username = 'admin';
$password = '123321';
$charset = 'utf8';
return [
'class' => \yii\db\Connection::class,
'dsn' => "mysql:host={$host}:{$port};dbname={$dbname}",
'username' => $username,
'password' => $password,
'charset' => $charset,
];
You can customize variables as you want, also you may write methods, before returning connection class, to get all needed variables.

Yii2 Failing to instantiate component or class "db"

I use a Yii2 console application to run migrations. It's a very basic app, that goes like this (yii.php in the / folder of the project):
<?php
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/config/console.php';
(new yii\console\Application($config))->run();
?>
So when i run
php yii.php
Everything's fine, but when i run
php yii.php migrate/create create_user_table
I am getting an error message:
Error: Failed to instantiate component or class "db".
My Yii is v2.0.15.1
UPD 19:32 30/12/2018
When I add a db config to a config/console.php like this:
return [
'id' => 'school-console',
'basePath' => dirname(__DIR__),
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=school',
'username' => 'root',
'password' => 'Taras1love',
'charset' => 'utf8',
]
];
I get this:
Error: Setting read-only property: yii\console\Application::db
You are missing the database component configurations for the console application you need to add the following inside the config/console.php file. As you are usign the basic-app for Yii2 you must have a db.php file with the database configurations, you need to include it like below
//this goes on the top of your `console.php` file
$db = require __DIR__ . '/db.php',
return [
'id' => 'myapp-console',
'basePath' => dirname(__DIR__)
//add the db component
'components' => [
'db' => $db,
]
];
Your db.php should be like below inside the config folder, change the values for the username, password and dbname.
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=YOUR_DB_NAME',
'username' => 'DB_USER',
'password' => 'DB_PASS',
'charset' => 'utf8',
];
or you can assign it inside the config/console.php if you dont want to create a separate file
return [
'id' => 'myapp-console',
'basePath' => dirname(__DIR__)
//add the db component
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=YOUR_DB_NAME',
'username' => 'DB_USER',
'password' => 'DB_PASS',
'charset' => 'utf8',
]
]
];
I found that I got this problem if I ran yii directly from vendor/bin.
If I went to the console directory and ran it from there using ./yii, I did not get this error and was able to create the migration.
In other words:
cd <project-root>/vendor/bin
yii migrate/create xxx
did not work
But:
cd <project-root>/console
./yii migrate/create xxx
did work
this happened to me because I accidentally renamed my migration and it was not matching the file name

Adding multiple connections in Laravel [duplicate]

I want to combine multiple databases in my system. Most of the time the database is MySQL; but it may differ in future i.e. Admin can generate such a reports which is use source of heterogeneous database system.
So my question is does Laravel provide any Facade to deal with such situations? Or any other framework have more suitable capabilities for problem is?
Tested versions (Updated)
Version
Tested (Yes/No)
4.2
No
5
Yes (5.5)
6
No
7
No
8
Yes (8.4)
9
Yes (9.2)
Define Connections
Using .env >= 5.0 (or higher)
In .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mysql_database
DB_USERNAME=root
DB_PASSWORD=secret
DB_CONNECTION_PGSQL=pgsql
DB_HOST_PGSQL=127.0.0.1
DB_PORT_PGSQL=5432
DB_DATABASE_PGSQL=pgsql_database
DB_USERNAME_PGSQL=root
DB_PASSWORD_PGSQL=secret
In config/database.php
'mysql' => [
'driver' => env('DB_CONNECTION'),
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
'pgsql' => [
'driver' => env('DB_CONNECTION_PGSQL'),
'host' => env('DB_HOST_PGSQL'),
'port' => env('DB_PORT_PGSQL'),
'database' => env('DB_DATABASE_PGSQL'),
'username' => env('DB_USERNAME_PGSQL'),
'password' => env('DB_PASSWORD_PGSQL'),
],
Note: In pgsql, if DB_username and DB_password are the same, then you can use env('DB_USERNAME'), which is mentioned in .env first few lines.
Without .env <= 4.0 (or lower)
app/config/database.php
return array(
'default' => 'mysql',
'connections' => array(
# Primary/Default database connection
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'mysql_database',
'username' => 'root',
'password' => 'secret'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# Secondary database connection
'pgsql' => [
'driver' => 'pgsql',
'host' => 'localhost',
'port' => '5432',
'database' => 'pgsql_database',
'username' => 'root',
'password' => 'secret',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
]
),
);
Schema / Migration
Run the connection() method to specify which connection to use.
Schema::connection('pgsql')->create('some_table', function($table)
{
$table->increments('id'):
});
Or, at the top, define a connection.
protected $connection = 'pgsql';
Query Builder
$users = DB::connection('pgsql')->select(...);
Model (In Laravel >= 5.0 (or higher))
Set the $connection variable in your model
class ModelName extends Model { // extend changed
protected $connection = 'pgsql';
}
Eloquent (In Laravel <= 4.0 (or lower))
Set the $connection variable in your model
class SomeModel extends Eloquent {
protected $connection = 'pgsql';
}
Transaction Mode
DB::transaction(function () {
DB::connection('mysql')->table('users')->update(['name' => 'John']);
DB::connection('pgsql')->table('orders')->update(['status' => 'shipped']);
});
or
DB::connection('mysql')->beginTransaction();
try {
DB::connection('mysql')->table('users')->update(['name' => 'John']);
DB::connection('pgsql')->beginTransaction();
DB::connection('pgsql')->table('orders')->update(['status' => 'shipped']);
DB::connection('pgsql')->commit();
DB::connection('mysql')->commit();
} catch (\Exception $e) {
DB::connection('mysql')->rollBack();
DB::connection('pgsql')->rollBack();
throw $e;
}
You can also define the connection at runtime via the setConnection method or the on static method:
class SomeController extends BaseController {
public function someMethod()
{
$someModel = new SomeModel;
$someModel->setConnection('pgsql'); // non-static method
$something = $someModel->find(1);
$something = SomeModel::on('pgsql')->find(1); // static method
return $something;
}
}
Note: Be careful about building relationships with tables across databases! It is possible to do, but it can come with caveats depending on your database and settings.
From Laravel Docs
Using Multiple Database Connections
You may access each connection via the connection method on the DB facade when using multiple connections. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file:
$users = DB::connection('foo')->select(...);
You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:
$pdo = DB::connection()->getPdo();
Useful Links
Laravel 5 multiple database connections FROM laracasts.com
Connect multiple databases in Laravel FROM tutsnare.com
Multiple DB Connections in Laravel FROM fideloper.com
In Laravel 5.1, you specify the connection:
$users = DB::connection('foo')->select(...);
Default, Laravel uses the default connection. It is simple, isn't it?
Read more here: http://laravel.com/docs/5.1/database#accessing-connections
Actually, DB::connection('name')->select(..) doesnt work for me, because 'name' has to be in double quotes: "name"
Still, the select query is executed on my default connection. Still trying to figure out, how to convince Laravel to work the way it is intended: change the connection.
Edit: I figured it out. After debugging Laravels DatabaseManager it turned out my database.php (config file) (inside $this->app) was wrong. In the section "connections" I had stuff like "database" with values of the one i copied it from. In clear terms, instead of
env('DB_DATABASE', 'name')
I needed to place something like
'myNewName'
since all connections were listed with the same values for the database, username, password, etc. which of course makes little sense if I want to access at least another database name
Therefore, every time I wanted to select something from another database I always ended up in my default database
Laravel has inbuilt support for multiple database systems, you need to provide connection details in config/database.php file
return [
'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'mysqlOne' => [
'driver' => 'mysql',
'host' => env('DB_HOST_ONE', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE_ONE', 'forge'),
'username' => env('DB_USERNAME_ONE', 'forge'),
'password' => env('DB_PASSWORD_ONE', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
];
Once you have this you can create two base model class for each connection and define the connection name in those models
//BaseModel.php
protected $connection = 'mysql';
//BaseModelOne.php
protected $connection = 'mysqlOne';
You can extend these models to create more models for tables in each DB.
Also you can use postgres fdw system
https://www.postgresql.org/docs/9.5/postgres-fdw.html
You will be able to connect different db in postgres. After that, in one query, you can access tables that are in different databases.
This worked for me
The Middleware:
<?php
namespace App\Http\Middleware;
use Config;
use Closure;
use DB;
class DBSelect
{
public function handle($request, Closure $next)
{
//$db_name = "db1";
$db_name = "db2";
Config::set('database.connections.mysql.database', $db_name);
DB::reconnect('mysql');
return $next($request);
}
}
global Kernel.php
protected $middleware = [
.....
\App\Http\Middleware\DBSelect::class,
];
I changed some code from this answer (https://stackoverflow.com/a/64744187/4514022) and it worked for me.
Not a good solution if you want to clone the existing system and to run the existing code on a new database for a new customer.
We would have to edit hundreds of eloquent calls to insert the DB::connection('foo')

Laravel create and change database in the same request

What I want to do is create a database with a request from the form.
Then connect to the database created and create a table inside.
on the same page and on the same request.
I do not know what to do because the env file and the database file are used when the page is opened and I can not enter values there.
$database_create_control=DB::statement('create database '.$prefix);
/*****/
Schema::create('companies', function (Blueprint $table) {
$table->increments('company_id');
$table->string('company_name',255);
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
});
the table I am connecting to is occurring in the database
but my wish was to work in the database I created a few lines ago.
After you create the database this is how you connect to it:
Config::set("database.connections.mysql", [
"host" => "...",
"database" => "...",
"username" => "...",
"password" => "...
]);
then do DB::purge('mysql');
then right after this do Schema::create('companies')... so you could use the new db
Config::set('database.connections.mysql', array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => $prefix,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
));
// and reconnect the DB class to the newly created version.
DB::reconnect();
this solution is work ! thanks #Hussein

Cakephp 3.0 ConnectionManager, getDataSource in Controller

In CakePHP 3.0, what's the equivalent of calling getDataSource() from inside a controller (like $this->ModelName->getDataSource()in cakephp 2.x)?
I have tried this:
use Cake\Datasource\ConnectionManager;
$conn = ConnectionManager::get('my_connection');
Since this connection is connected already, why do I need to provide 'my_connection'?
How can I can get the DataSource from inside a Controller in CakePHP 3.0?
Thanks
Database\ConnectionManager::get() has been added. It replaces getDataSource()
CakePHP Cookbook 3
Begin, commit and rollback are now functions on the connection, not the data source. Use $conn = ConnectionManager::get($connectionName) and then use $conn->begin(), $conn->commit() and $conn->rollback().
http://book.cakephp.org/3.0/en/orm/database-basics.html#using-transactions
And use $this->Table->defaultConnectionName() to get the connection name to pass to get.
"my_connection" should be defined in cakephp 3 config
.go to cakephp/config/app.php
'Datasources' => [
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
/**
* CakePHP will use the default DB port based on the driver selected
* MySQL on MAMP uses port 8889, MAMP users will want to uncomment
* the following line and set the port accordingly
*/
//'port' => 'non_standard_port_number',
'username' => 'root',
'password' => '',
'database' => 'cake',
'encoding' => 'utf8',
'timezone' => 'UTC',
'flags' => [],
'cacheMetadata' => true,
'log' => false,
connection name is "default" for this case.
Each Model that used in controller have one Connection.
You can get connection in controller from model by this method.
$model=TableRegistry::get('table_name');
$connection = $model->connection();