Gotenks
Gotenks

Reputation: 377

Remote MySQL Server connection w/PHP

I need to connect to an external MySQL database and fetch some data. I have a few concerns about it:

  1. Connecting to a remote server will increase the loading time of the page, I want that to be the lowest as possible.
  2. The data I need to load is extra, if the remote server appears to be down I don't want to wait extra time (until it times out).

What are the best practices on connecting to a remote MySQL database using PHP? Basically, I want my website loading time to be affected as smallest as possible.

If it can't be done with PHP, I'm open to a different approach.

Upvotes: 1

Views: 443

Answers (2)

LexLythius
LexLythius

Reputation: 1944

You might try MYSQLI_OPT_CONNECT_TIMEOUT option for mysqli_real_connect. It has had some quirks though, check this out.

That said, I concur with @tadman, building a server API is probably the best option. Synchronous calls to unreachable remote servers will render your own service unusable for all practical purposes.

Upvotes: 0

tadman
tadman

Reputation: 211540

If possible, build an API for one end which has local access to the database, and an API consumer at your remote. Then you can institute a time-out on the API fetch call. Writing a simple JSON-type wrapper around a database is not usually that difficult.

The alternatives are messy, such as a VPN, an SSH bridge, or remote access to the MySQL port using SSL/TLS for encryption. The database driver will struggle when you have an unreliable connection, or one that suffers packet loss. Performance will be erratic at best.

Upvotes: 1

Related Questions