PHP code example of corn / mypdoms

1. Go to this page and download the library: Download corn/mypdoms library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

corn / mypdoms example snippets



use Corn\MyPDOMS\MyPDOMS;

MyPDOMS::setConfig([
	'my_site_1' => [
		'master' => [
			'host' => '127.0.0.1',
			'port' => 3306,
			'username' => 'my_site_user',
			'password' => 'apples'
		],
		'slaves' => [
			'slave_1' => [
				'host' => '10.0.1.1',
				'username' => 'slave_user',
				'password' => 'readonly'
			],
			'slave_2' => [
				'host' => '10.0.1.2',
				'username' => 'slave_user',
				'password' => 'readonly'
			]
		]
	],
	'my_site_2' => [
		'master' => [
			'host' => 'localhost',
			'username' => 'my_site_2_user',
			'password' => 'oranges'
		]
	]
]);


use Corn\MyPDOMS\MyPDOMS;

$db = new MyPDOMS('mysql:host=my_site_1;dbname=my_database;charset=utf8mb4', null, null, [MyPDOMS::ATTR_TIMEOUT => 5]);


use Corn\MyPDOMS\MyPDOMS;

$db = new MyPDOMS($dsn);
$db->query("/*" . MyPDOMS::HINT_MASTER . "*/SELECT 1"); // will be sent to the master even though it's a SELECT


use Corn\MyPDOMS\MyPDOMS;

if (!defined('MYSQLND_MS_MASTER_SWITCH')) {
	define('MYSQLND_MS_MASTER_SWITCH', MyPDOMS::HINT_MASTER);
	define('MYSQLND_MS_SLAVE_SWITCH', MyPDOMS::HINT_SLAVE);
	define('MYSQLND_MS_LAST_USED_SWITCH', MyPDOMS::HINT_LAST_USED);
}


use Corn\MyPDOMS\MyPDOMS;

// Assume configured slaves are slave_{1-5}

$db = new MyPDOMS($dsn);
$db->query("SELECT 1");
echo $db->lastUsedHost . "\n"; // slave_4
$db->query("SELECT 1");
echo $db->lastUsedHost . "\n"; // slave_3
$db->query("SELECT 1");
echo $db->lastUsedHost . "\n"; // slave_4
$db->query("SELECT 1");
echo $db->lastUsedHost . "\n"; // slave_2
$db->query("SELECT 1");
echo $db->lastUsedHost . "\n"; // slave_2
$db->query("SELECT 1");
echo $db->lastUsedHost . "\n"; // slave_2


use Corn\MyPDOMS\MyPDOMS;

$db = new MyPDOMS($dsn);
$stmt = $db->prepare("SELECT 1");
echo $db->lastUsedHost . "\n"; // slave_1

$db->query("SELECT 1");
echo $db->lastUsedHost . "\n"; // slave_2

$stmt->execute(); // this is executed on slave_1 since it was prepared on slave_1
echo $db->lastUsedHost . "\n"; // slave_2

$db->query("/*" . MyPDOMS::HINT_LAST_USED . "*/ SELECT 1");
echo $db->lastUsedHost . "\n"; // slave_2