ATLChris
ATLChris

Reputation: 3296

Change IP of PHP PDO MySQL connection based on network

I just setup an environment via Vagrant for consistency across 2 development laptops. I am using a remote MySQL server (home server) with PHP PDO. I wanted to know if I can use PHP to determine if I am on the local network as the MySQL server and connect to it via 192.168.1.111 or if I am not on the same network as the MySQL server and connect to it through *.dyndns.org.

I have the local and remote connections setup correctly and they are both working.

How can I use PHP to connect to the MySQL server locally if it is available, but if not via the remote address?

$pdo = new PDO('mysql:host=' . DB_IP . ';port=' . DB_PORT . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);

Upvotes: 2

Views: 1447

Answers (1)

xate
xate

Reputation: 6379

Can't you just try something like this?!:

$opt = array(
   PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);

try
{
   $dsn = "mysql:host=localhost;dbname=test;charset=utf8";
   $pdo = new PDO($dsn,'root','', $opt);
}
catch (PDOException $e)
{
   $dsn = "mysql:host=yourRemoteHost;dbname=testRemoteHost;charset=utf8";
   $pdo = new PDO($dsn,'root','', $opt);
}

Like this you try to connect to localhost and if it does not work, you catch the exception and connect to the remote. Just use your data for mysql:host etc.

Christian Gollhardt mentioned that you could probably use the "Throw new Exception..." way if you are in dev state. But that shouldn't be an Exception anymore if you are in product environment - you will have to rebuild this part of code anyways then.

Upvotes: 7

Related Questions