I am trying to use database connection inside my model but it was not getting connected throwing error as "Class 'app\models\DB' not found". I have created a common model to be extended by all my models inside modules that means all models extends the CommonModel, I am getting this error inside the CommonModel. I have read yii documentation regards database connection & googled for the same but I din't find any solution. My code is:
models\CommonModel.php
namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
use yii\db\Query;
use app\models\Mailsettings;
use \PDO as PDO;
class CommonModel extends \yii\db\ActiveRecord{
protected $_db;
protected $_sql;
public function __construct()
{
$this->_db = DB::init(); // This line causing the error
$pdo = Timetrackdb::getPdoConnection();
}
----
----
}
config/db.php & config/db2.php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=my_db_name',
'username' => 'db_username',
'password' => 'db_password',
'charset' => 'utf8',
];
config/web.php
$db = require __DIR__ . '/db.php';
$db2 = require __DIR__ . '/db2.php';
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'modules' => [
'my_module1' => [
'class' => 'app\modules\my_module1'
],
'my_module2' => [
'class' => 'app\modules\my_module2'
],
],
------
------
'db' => $db,
'db2' => $db2,
------
------
];
I have created 2 modules in which one module is working fine with the same type of database connection but the other module's db connection is not working properly. Can anyone please tell whats wrong with this code? Thanks.
Yii deals with connecting to databases for you, you don't need PDO. Just access Yii::$app->db2 if you want to have CommonModel or derived ActiveRecord classes to use the second database as their data store:
class CommonModel extends ActiveRecord {
public static function getDb()
{
// this will cause Yii to use the database configured as 'db2' in config/web.php
return Yii::$app->db2;
}
}
class Car extends CommonModel { }
// will try to insert a new row in `db2`.`car`
(new Car)->save();
You may also need to do the following if you're going to perform cross-schema queries (config/db2.php):
return [
// ...
// add and adjust the keys below
'tablePrefix' => '',
'schemaMap' => [
'mysql' => [
'class' => 'yii\db\mysql\Schema',
'defaultSchema' => 'my_db_name',
],
],
];
Related
it's me again. I have a problem saving data to the database from the input form that I made.
Here is my web route:
Route::get('/admin/data-karyawan', [BasicKaryawanController::class, 'data_karyawan']);
Route::get('/admin/create', [BasicKaryawanController::class, 'index']);
Route::post('/admin/create', [BasicKaryawanController::class, 'simpan']);
Here is my controller:
class BasicKaryawanController extends Controller
{
public function data_karyawan()
{
return view('data-karyawan', [
"title" => "Data Karyawan",
"karyawan" => Karyawan::with(['role', 'user'])->search(request(['search']))->paginate(10)
]);
}
public function index()
{
return view('create', [
"title" => "Tambah Karyawan"
]);
}
public function simpan(Request $request)
{
$validatedData = $request->validate([
'nik' => 'required|max:7',
'nama' => 'required|max:255',
'jk' => 'required|max:1',
'tempat_lahir' => 'required|max:255',
'tanggal_lahir' => 'required|max:255',
'alamat' => 'required|max:255',
'agama' => 'required',
'jabatan' => 'required|max:255',
'id_jabatan' => 'required|max:1',
'divisi' => 'required',
'email' => 'required|email:dns|unique:karyawans',
'password' => 'required|min:5|max:255'
]);
$validatedData['password'] = bcrypt($validatedData['password']);
Karyawan::create($validatedData);
return view('data-karyawan', [
"title" => "Data Karyawan",
"karyawan" => Karyawan::with(['role', 'user'])->search(request(['search']))->paginate(10)
]);
}
and this is my form blade view:
https://codeshare.io/3AzKD1
The code is running well but the form is not saving the data I input from the form to the database. Did I miss something?
Thank you.
This is solved.
I need to fill all the field on the table so it can store to the database.
Yes right, if u r using eloquent create method which accepts an array of attributes, creates a model, and inserts it into the database. The difference between save and create is that save accepts a full Eloquent model instance while create accepts a plain PHP array.
U can take the reference from here
I'm trying to implement cakephp authentication plugin in admin prefix
Route I have written for admin prefix
$routes->prefix('admin', function (RouteBuilder $routes) {
$routes->connect('/',['controller'=>'AdminUsers','action'=>'login']);
$routes->fallbacks(DashedRoute::class);
});
In application.php , I have followed everything That mentioned in authentication documentation
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$authenticationService = new AuthenticationService([
'unauthenticatedRedirect' => Router::url('/admin'),
'queryParam' => 'redirect',
]);
// Load identifiers, ensure we check email and password fields
$authenticationService->loadIdentifier('Authentication.Password', [
'fields' => [
'username' => 'email',
'password' => 'password',
]
]);
// Load the authenticators, you want session first
$authenticationService->loadAuthenticator('Authentication.Session');
// Configure form data check to pick email and password
$authenticationService->loadAuthenticator('Authentication.Form', [
'fields' => [
'username' => 'email',
'password' => 'password',
],
'userModel' => 'AdminUsers',
'loginUrl' => Router::url('/admin'),
]);
return $authenticationService;
}
I have changed users model to AdminUsers for database table admin_users
Now in admin/appController.php
I have loadComponent in initialize method
$this->loadComponent('Authentication.Authentication');
In before filter method I have added
$this->Authentication->allowUnauthenticated(['login']);
Now after submit login form I am getting error
Table class for alias Users could not be found.
In getAuthenticationService method I have changed model Users to AdminUsers. Why it's going for Users model rather then AdminUsers model ?
My Table/AdminUsersTable.php table class look likes
<?php
declare(strict_types=1);
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class AdminUsersTable extends Table
{
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('admin_users');
--------
After ndm comment I am able to change default model in application.php , But how can I change it in Admin/AppController.php ? Code that I have tried.
public function beforeFilter(EventInterface $event)
{
$service = new AuthenticationService();
$service->loadIdentifier('Authentication.Password', [
'resolver' => [
'className' => 'Authentication.Orm',
'userModel' => 'AdminUsers',
],
]);
$this->Authentication->allowUnauthenticated(['login','signup']);
$this->viewBuilder()->setLayout('admin');
}
In our app, we are handing all error and inserting in tbl_error_log table. But due to some reason it has stopped work and now no error is inserting in error_log table except initialize function error. If error in initialize function then it is working. We are using below code for inserting error.
File path : Vendor/Cakephp/Cakephp/src/Error/BaseErrorhandler.php
protected function _logError($level, $data) {
$ErrorLogTable = TableRegistry::get('tbl_error_log');
$errorlog = $ErrorLogTable->newEntity();
$errorlog->in_user_id = $User['member_id'];
$errorlog->st_email_address = $User['email'];
$errorlog->in_error_no = $data['code'];
$errorlog->st_error_type = $data['error'];
$errorlog->st_error_string = $data['description'];
$errorlog->st_error_file = $data['file'];
$errorlog->in_error_line_no = $data['line'];
$errorlog->dt_error_time = new \DateTime('now');
$errorlog->st_from_ip = $this->getClientIp();
$ErrorLogTable->save($errorlog);
}
I can't speak about your problem with errors only logged from certain code parts, but generally that's not how to do custo logging. Never modify vendor files (unless for testing purposes of course), they will eventually be overwritten when updating the dependencies.
If you want to implement custom logging functionality, then create a custom logger as shown in the docs:
// src/Log/Engine/DatabaseLog.php
namespace App\Log\Engine;
use Cake\Log\Engine\BaseLog;
class DatabaseLog extends BaseLog
{
public function __construct($options = [])
{
parent::__construct($options);
// ...
}
public function log($level, $message, array $context = [])
{
// Write to the database.
}
}
See Cookbook > Logging > Creating Log Adapters
You can use it as the default logger by changing the configuration in your config/app.php file accordingly:
'Log' => [
'debug' => [
'className' => 'Database',
'scopes' => false,
'levels' => ['notice', 'info', 'debug'],
],
'error' => [
'className' => 'Database',
'scopes' => false,
'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
],
// ...
],
When I was using ZF1, I had an ini file with db connection information (i.e. mysql, pgsql, mssql, etc...)
modulename.adapter = PDO_MYSQL
modulename.params.host = xxx.xxx.x.xx
modulename.params.username = username
modulename.params.password = password
modulename.params.dbname = databasename
and in my model, I would extends Zend_Db_Table and do the following in my
public function _construct() {
$dbconfig = Zend_Registry::get('dbProfiles');
$this->db = Zend_Db::factory($dbconfig->modulename->adapter,
$dbconfig->modulename->params);
}
in some function, I have the following code
$sql = "SELECT * FROM Table";
$result = $this->db->query($sql);
while($row =$result->fetch()) {
//... do something
}
How can I do something similar to this in ZF3? Connecting multiple database types, querying different tables, and fetching my results?
Thank you.
In your configuration set as many database adapters as you have databases:
'db' => [
'adapters' => [
'Application\Db\Db1Adapter' => [
'driver' => 'Pdo_Mysql',
'Dsn' => 'mysql:dbname=Your_db_1_name;host=your_host;charset=utf8',
'password' => 'your_password',
'username' => 'your_username',
],
'Application\Db\Db2Adapter' => [
'driver' => 'Pdo_Mysql',
'Dsn' => 'mysql:dbname=Your_db_2_name;host=your_host;charset=utf8',
'password' => 'your_password',
'username' => 'your_username',
]
]
],
Then call the adapter in service manager factories to create tablegateway or just pass the adapter to the controller:
use \Application\Db\Db1Adapter;
...
$db1Adapter = $container->get(Db1Adapter::class);
...
I have a problem with Kohana database.
Sometimes I have error
ErrorException [ Recoverable Error ]
Argument 1 passed to Kohana_Database_Query_Builder_Select::compile() must be an instance of Database, string given, called in /srv/sites/mysite/www/modules/database/classes/kohana/database/query.php on line 230 and defined
It's happens because in Database:$instances containts string "dances", but should contain array database configurations.
This my config:
<?php defined('SYSPATH') OR die('No direct access allowed.');
return array
(
'default' => array
(
'type' => 'MySQL',
'connection' => array(
'hostname' => 'localhost',
'database' => 'chat',
'username' => 'root',
'password' => 'root',
'persistent' => FALSE,
),
'table_prefix' => '',
'charset' => 'utf8',
'caching' => FALSE,
'profiling' => TRUE
)
);
Maybe somebody had problem like this or could help me?
Any query to DB causes error.
Like this:
Jelly::factory('user', $user->id())
or this:
DB::select('value')->from('storage')->where('name', '=', 'salt')->limit(1)->execute();
or this:
ORM::factory('node')->where('type', '=', 'page-homepage')->find();
I don't know why this error happen. I checked all methods are called and I have not found any mistakes.
I solved this problem by write method instance in class Database
public static function instance($name = NULL, array $config = NULL)
{
if ($name === NULL)
{
// Use the default instance name
$name = Database::$default;
}
if ( ! is_array(Database::$instances))
{
Database::$instances = array();
}
if ( ! isset(Database::$instances[$name]))
{
if ($config === NULL)
{
// Load the configuration for this database
$config = Kohana::$config->load('database')->get($name);
}
if ( ! isset($config['type']))
{
throw new Kohana_Exception('Database type not defined in :name configuration',
array(':name' => $name));
}
// Set the driver class name
$driver = 'Database_'.ucfirst($config['type']);
// Create the database connection instance
new $driver($name, $config);
}
return Database::$instances[$name];
}
I add condition As you can see
if ( ! is_array(Database::$instances))
{
Database::$instances = array();
}
I don't like this, but I have no choise.
My wild guess would be that you seem to be overwriting the compile, quote, quote_column, quote_identifier, quote_table or execute method from Kohana_Database in your code or simply calling ->execute('dances') should trigger this error.
the compile method shouldn't be called directly, it's an internal function that is called from execute()
Any of these functions take $db as the first parameter. Don't pass anything, since you want to use the database set in your config file, without trying to set it manually in your query builder.