if run to a delemia when im out of the hosue and not near a net work i want to be able to run on local, but i dont want to have to change the credientials is there a way i can have it try one and if it snt that or if its neither then send an error code?

Dani AI

Generated

Building on 's idea of checking availability first, a robust pattern is: keep both credential sets in config (prefer environment variables), try the remote DB with a short connect timeout, and only if that fails attempt the local DB. That avoids long hangs when the network is flaky and keeps credentials unchanged for your app.

A compact mysqli example — try the primary, then fallback. Adjust timeout and credential sources to fit your app:

<?php
$sets = [
    ['host'=>'db.example.com','user'=>'remote_user','pass'=>'remote_pass','db'=>'mydb','port'=>3306],
    ['host'=>'127.0.0.1','user'=>'local_user','pass'=>'local_pass','db'=>'mydb','port'=>3306],
];

$timeout = 3;

function try_connect($cfg, $timeout) {
    $m = mysqli_init();
    mysqli_options($m, MYSQLI_OPT_CONNECT_TIMEOUT, $timeout);
    if (@mysqli_real_connect($m, $cfg['host'], $cfg['user'], $cfg['pass'], $cfg['db'], $cfg['port'])) {
        return $m;
    }
    mysqli_close($m);
    return false;
}

$conn = null;
foreach ($sets as $cfg) {
    if ($link = try_connect($cfg, $timeout)) { $conn = $link; break; }
}

if (!$conn) {
    http_response_code(503); // or your custom error code/handling
    exit('Database unavailable');
}
?>

Notes and cautions: use 127.0.0.1 instead of "localhost" to avoid socket vs TCP differences; store creds in environment variables or a protected config file, not in source control; give each environment a least-privilege DB user; log failures for debugging. If needed, pre-check host:port reachability with a quick socket test (fsockopen) before attempting a full DB connection. This keeps the fallback predictable and minimizes user-visible delays.

Recommended Answers

All 3 Replies

So what you are asking is, is there a way to check a networked SQL connection for status without having a network connection?

Perhaps reword your question a little?

Basically I'm trying to connect to the database and try two sets of login credentials,

if you have an internet connection all you have to do is instantiate a connection as normal, then check to see if the resource is available.

If it's not available, try the other one...

Im not quite sure I follow what your plan of attack is...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.