How to include external PHP file in Magento?
Can we include this file in event-observer model's Observer.php file?
How can we execute external PHP file in Magento?
Including another class can easily be achieved by just making an extension for the classes used. Then just use standard Magento class loading techniques to access them:
Mage::getModel('mynamespace/mymodule')->myFunction()
Mage::helper('mymodulefrontname')->myFunction()
It would also be worth considering creating the MySQL connection through Zend/Varien itself. Here is a starter function:
protected function _initiateDbConnection()
{
$configs = array('model' => 'mysql4', 'active' => '1', 'host' => 'localhost', 'username' => '', 'password' => '', 'dbname' => '', 'charset' => 'utf8');
return Mage::getSingleton('core/resource')->createConnection('mymodule_read', 'pdo_mysql', $configs);
}
Which will give you an Zend DB instance that you can execute query() etc. on.
Related
I'm trying to change the database connection used in cakephp 3 on the fly. Every answer to this question that I found refers to cakephp 2 (These three for instance).
This guy found a solution for cakephp 3 having a finite number of databases, and specifically defining which Database would be used by which Table file.
The thing is that I want to create a new database for every new user, and change to his database when he logs in. I can't know in advance all the databases that will exist, to write it in the config/app.php file.
And I can't set the default database in each /src/Model/Table file, because the tables are the same in every database.
Use the ConnectionManager::config() function to create connections on the fly and the ConnnectionManager::alias() method to make all your Table classes use it by default.
There is a very good article describing the process here:
http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database
The only difference is that you can create the connection config on the fly instead of declaring the shards manually as it was shown in that article.
Change database connection for one model:
In app.php :
'test' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => MySQL_HOST,
//'port' => 'nonstandard_port_number',
'port' => MySQL_PORT,
'username' => MySQL_USER,
'password' => MySQL_PASS,
'database' => 'test',
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
'log' => false,
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
]
In Controller :
$conn = ConnectionManager::get('test');
$_model = TableRegistry::get('your_alias', ['table' => 'your_table', 'connection' => $conn]);
Configuring table connections
namespace App\Model\Table;
use Cake\ORM\Table;
class ArticlesTable extends Table
{
public static function defaultConnectionName() {
return 'replica_db';
}
}
This question already has answers here:
How to connect to mysql with laravel?
(6 answers)
Closed 8 years ago.
I'm making a PHP application installer (something like Wordpress installation script) and I need to check mysql connection using host name, username, password and database provided by user during installation.
I'm using this code as a Laravel controller method to test connection:
public function TestDatabaseConnection(){
try {
$database_host = Config::get('config.database_host');
$database_name = Config::get('config.database_name');
$database_user = Config::get('config.database_user');
$database_password = Config::get('config.database_password');
$connection = mysqli_connect($database_host,$database_user,$database_password,$database_name);
if (mysqli_connect_errno()){
return false;
} else {
return true;
}
} catch (Exception $e) {
return false;
}
}
This code doesn't seem to properly test the connection. Function return value (true/false) doesn't depend whether user supplies db data at all, or if db data is correct/incorrect..
Fils /app/config/config.php contains the following array:
<?php return array('database_host' => 'localhost', 'database_name' => 'dbasename', 'database_user' => 'dbuser', 'database_password' => 'pass');
and it's being updated via form during installation process.
Is there any way to modify this code or maybe you have some other code suggestions?
Your question is:
How to test MySQL connection in PHP and Laravel?
But then you are setting up a standard PHP MySQLi connection like this:
$connection = mysqli_connect($database_host,$database_user,$database_password,$database_name);
Why would you do that? The whole purpose of using a framework is to work within the framework. And something that encompasses these two basic systems concepts:
Read a configuration file.
Establish a database connection.
Doing those things is something that pretty much every capable—and widely adopted—programming framework should be able to handle within it’s own structure & using it’s own methods.
So that said, looking at the Laravel documentation on “Basic Database Usage” shows the following. This is placed in your DB configuration file located in app/config/database.php.:
'mysql' => array(
'read' => array(
'host' => '192.168.1.1',
),
'write' => array(
'host' => '196.168.1.2'
),
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
The example has two distinct DB connections: One for read and the other for write, but that is not how most DB connections for simple projects work. So you can set this instead also using your settings:
'mysql' => array(
'host' => Config::get('config.database_host'),
'driver' => 'mysql',
'database' => Config::get('config.database_name'),
'username' => Config::get('config.database_user'),
'password' => Config::get('config.database_password'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
Then to test that connection, you would just do this:
if(DB::connection()->getDatabaseName())
{
echo "Yes! successfully connected to the DB: " . DB::connection()->getDatabaseName();
}
But that said you are also saying:
I'm making a PHP application installer…
Why reinvent the wheel when PHP build systems such as Phing exist?
You can simply check whether the connection is made or not using this:
if(DB::connection()) {
// connection is made
}
Because you don't need to make connection manually. If the user provided right credentials in the app/config/database.php then the user will be able to query in the database but if you need to check the connection then given code above is able to check because if the connection is not made then an error will be thrown and on a valid connection the Illuminate\Database\MySqlConnection object will be returned. So, in this case it's also possible to use:
if(DB::connection() instanceof Illuminate\Database\MySqlConnection) {
// connection is made
}
So, according to your example of TestDatabaseConnection method you can do something like this:
public function TestDatabaseConnection(){
// Returns Illuminate\Database\MySqlConnection on successful
// connection; otherwise an exception would be thrown if failed
return DB::connection();
}
If you really want to catch the error of laravel db connection failure,
you can define this:
App::error(function(PDOException $exception, $code)
{
die('do what you want here');
});
I defined it inside:
/app/start/global.php
you can define it where ever you like.
I want to connect to another database sometimes.
I created a config.php with the database connection data.
But how can i tell laravel to connect to this database insted of using the config/database.php?
For example when using the Schema class.
Since no one seems to understand what i want.
I DON'T want to use the config/database.php, i want to use a different config file on a different location.
It sounds like you figured this out. Here's how I'd accomplish it anyway for other people coming in, or in case something useful is here for you.
First, Add a second connection in app/config/database.php. Note: That file path may change depending on your environment.
<?php
return array(
'connections' => array(
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'mysql2' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
Second, in your code, you can use (as mentioned) the 2nd connection where you would like:
Schema::connection('mysql2')->create('users', function($table) {})
There's more documentation on this - see Accessing Connections.
Eloquent ORM
You can define the variable for "connection" in an eloquent class to set which connection is used. That's noted in the Basic Usage section.
See that variable on here on Github and the method which you can set to set the connection dynamically here.
Edit
The OP has made it clear that they do not wish to use the config/database.php file for config.
However without explaining further, I can't comment. I'm happy to help - sounds like it would be useful to know why the config/database.php file can't/shouldn't be used, as this can help us ascertain the problem and create a useful solution.
I believe you want to implement some kind of logical sharding where databases would be dynamically created.
In such scenario in laravel you can dynamically add a database config, like below
$conn = array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'DATABASE',
'username' => 'USERNAME',
'password' => 'SOME_PASSWORD',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
);
Config::set('database.connections.DB_CONFIG_NAME', $conn);
Now to connect via eloquent
MODEL::on('DB_CONFIG_NAME')->WHAT_EVER('1');
Incase of Query Builder you can do
$DB = DB::connection('DB_CONFIG_NAME');
use $DB->select() for querying now.
Hope this would help devs looking for a possible solution for this question
Remember that Laravel 4 is actually a collection of components, and you can use these components solo.
https://github.com/illuminate/database
There is an example here that shows off how interacting with the Capsule class works:
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]);
// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Set the cache manager instance used by connections... (optional)
$capsule->setCacheManager(...);
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
This is a bunch of bootstrapping that you'll need to run, so tuck it away somewhere in a function or method.
But, its absolutely possible.
There is a simpler solution. If you are using Larave 4 there is an option that worked for me. Recently they added $table variable that you can specify in your model. Refer to this link.
class User extends Eloquent {
protected $table = 'my_users';
}
If you are using MySQL, you can do the following:
class User extends Eloquent {
protected $table = 'mydbname.my_users';
}
If you are using SQL Server, you can do this:
class User extends Eloquent {
protected $table = 'mydatabase..my_users';
}
My Config file had DB1 specified but I created a model which wants to access DB2 in the same MySQL host. So this was a quick and dirty way to accomplish this.
Now I don't fully leverage Eloquent ORM all the time so this "hack" may not work with Many to Many or one to Many Eloquent methods.
One another idea I had but I didn't actually try was creating a stored procedure (routine) in DB1 and inside of that routine I can access DB2 tables by querying link this:
SELECT * from db2.mytable where id = 1;
To use a config file in another location, say src/config:
use Config;
$this->dbConfig = Config::get('appname::dbInfo.connections.test');
$this->database = $this->dbConfig['database'];
$this->username= $this->dbConfig['username'];
$this->password= $this->dbConfig['password'];
Where dbInfo is a simple php file in your app's src/config directory returning an array containing the element connections which is an array of database properties.
You can tell Laravel to use an external config file using:
Config::set("database.connections.test", $this->dbConfig);
DB::connection("test");
Edit bootstrap/start.php file and add your machine name (open terminal: hostname).
Add your machine to $env,
$env = $app->detectEnvironment(array(
'mymachine' => array('mymachine.local'),
));
Create a new path at 'app/config/mymachine'
Add a copy of database.php with new config params.
I'm trying to write a script for laravel that queries
my database and fetches tables, but I'm not sure what to include
in the file in order to get the DB class to work.
Thus far my code looks like:
$tables = DB::query("SHOW TABLES");
foreach ($tables as $table) {
print $table . "\n";
}
I've tried using require "../../vendor/autoload.php" but that doesn't help.
So for instance, the DB class works fine if I call it within a controller, but not
if I create a directory, say /application/scripts and create a file test.php .
If I try to call DB in that file, the DB class isn't defined (for good reason).
I'm wondering what I need to require in that file in order for that class to be defined.
I would suggest using the Illuminate/Database package (part of Laravel 4). You won't get the DB interface, because that's a special facade provided by the Laravel Framework, but all the query builder functionality is available through the capsule.
Install illuminate/database using composer and then follow the included readme notes (included below for completeness).
Illuminate Database
Usage Outside Of Laravel 4
$config = array(
'fetch' => PDO::FETCH_CLASS,
'default' => 'mysql',
'connections' => array(
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'laravel',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
$capsule = new Illuminate\Database\Capsule($config);
// If you want to use the Eloquent ORM...
$capsule->bootEloquent();
// Making A Query Builder Call...
$capsule->connection()->table('users')->where('id', 1)->first();
// Making A Schema Builder Call...
$capsule->connection()->schema()->create('users', function($t)
{
$t->increments('id');
$t->string('email');
$t->timestamps();
});
You do not need to include anything. Laravel will include what it needs and setup the system itself. You are using a variable called $db but it is not defined and means/does nothing. What you are looking for is the DB class. Try this:
$tables = DB::query('SHOW TABLES');
foreach ($tables as $table)
{
echo $table.PHP_EOL;
}
Also, check out the Fluent DB class documentation:
http://laravel.com/docs/database/fluent
...Isn't it DB::query()? A call to the database engine is through a class, not a variable, for scoping issues.
I am new to Zend. I'm using Zend 1.11 and trying to successfully connect to a Firebird database. As far as I can tell I have all the php_interbase stuff enabled. I see the ZendX firebird adapter, but I still get this message
Warning: include_once(Zend\Db\Adapter\Php\Firebird.php)
[function.include-once]: failed to open stream: No such file or
directory in C:\wamp\bin\php\Zend_Framework\library\Zend\Loader.php on
line 146
As if it has no idea what adapter I'm speaking of.
I'm using this in my boot strap
protected function _initDb()
{
$this->bootstrap('config');
$config = $this->getResource('config');
$db = Zend_Db::factory('Php_Firebird', array(
'host' => $config->Database->Server,
'username' => $config->Database->Username,
'password' => $config->Database->Password,
'dbname' => $config->Database->DBName
));
return $db;
}
I'm assuming this has something to do with the fact this is ZendX stuff not Zend\db stuff but I cannot find an example of it. Or from the factory function using a ZendX adapter. I tried to use 'Php_Interbase' but that was not found either (and I dont see it in the folders anyway). And I tried Pdo_Firebird as well which of course didnt work.
Has someone done this that can point me to what I'm doing wrong?
Thanks
You just need to add adapterNamespace to the configuration array you are passing to the factory. See the 3rd example here, also remove 'PHP_' from the adapter name, so your call to the factory should look like this:-
$db = Zend_Db::factory('Firebird', array(
'host' => $config->Database->Server,
'username' => $config->Database->Username,
'password' => $config->Database->Password,
'dbname' => $config->Database->DBName,
'adapterNamespace' => 'ZendX_Db_Adapter'
));
Try something like
$db = new ZendX_Db_Adapter_Firebird(array(
//config part
));