connecting to alternate database when primary database is down? - php

$servername1 = "localhost1";
$username1 = "user1";
$password1 = "pwd";
$dbname1 = "dbs1";
$servername2 = "localhost2";
$username2 = "user2";
$password2 = "ped2";
$dbname2 = "dbs2";
// Create connection
$conn = new mysqli($servername1, $username1, $password1, $dbname1);
// Check connection
if ($conn->connect_error) {
$conn = new mysqli($servername2, $username2, $password2, $dbname2);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
}
Can this type of connection be implemented?? when i implement this deliberately making an error in first database credentials i get a warning that Unknown MySQL server host 'localhost1'
and doesn't load the page. why is this not working?

I make a list of databases and then iterate through them and try to connect. It should be no problem using multiple databases. Using localhost1 and localhost2 (only localhost is possible which is 127.0.0.1) is not possible. You should use IP addresses.
Here is the code:
<?php
$Databases = array(
0 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database1',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_3,
),
1 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database2',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_2,
),
2 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database3',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_1,
),
);
for($i=0;$i<count($Databases);$i++)
{
if($last_db_ind>=count($Databases)){
$last_db_ind=0;
}
if(($db =& db_connect($last_db_ind++))==false){
echo 'Connection failed for DB: '. $Databases["db_name"] . ', DB index: '.$last_db_ind;
continue;
}
?>

You should either use "localhost" or an IP address to connect to the SQL server. In your case it tries to connect to "localhost1" (as in you variable) which doesn't exists (unless you changed your host file). Try using IPs (127.0.0.1 for localhost and any other for the backup)
Cheers,
JCK

You Can try Ping first.
OR
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ")
" . $mysqli->connect_error;
}
OR
extension_loaded("mysql");

Related

Cannot connect to SAP using PHP sapnwrfc with Connection Type Group

I cannot connect to SAP using PHP sapnwrfc, this is my code :
use SAPNWRFC\Connection as SapConnection;
use SAPNWRFC\Exception as SapException;
$config = [
'GROUP' => '*****', // Group/Server
'MSHOST' => '*****', // Message Server
'CLIENT' => '*****', // System ID
'SYSNR' => '*****', // Instance Number
'USER' => '*****', // Username
'PASSWD' => '*****', // Password
'SAPROUTER' => '*****', // SAP Router
'TRACE' => SapConnection::TRACE_LEVEL_OFF, // Trace
];
try {
$c = new SapConnection($config);
$f = $c->getFunction('*****');
$result = $f->invoke();
echo "<pre>";
print_r($result);
echo "<pre>";
} catch(SapException $ex) {
echo 'Exception: ' . $ex->getMessage() . PHP_EOL;
}
Is there something wrong? Please help me.
Thankyou in advance.

Laravel MS SQL Login timeout expired

I'm running Ubuntu 18.04 with nginx & php-fpm
In laravel I try to connect to a external MS SQL Server.
My .env database settings:
DB_CONNECTION=sqlsrv
DB_HOST=127.20.2.10
DB_PORT=1433
DB_DATABASE=DATA
DB_USERNAME=saWeb
DB_PASSWORD='PASSWORD'
My config/database.php:
'default' => env('DB_CONNECTION', 'sqlsrv'),
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', '127.20.2.10'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'DATA'),
'username' => env('DB_USERNAME', 'saWeb'),
'password' => env('DB_PASSWORD', 'PASSWORD'),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
],
Laravel got the error:
SQLSTATE[HYT00]: [unixODBC][Microsoft][ODBC Driver 17 for SQL
Server]Login timeout expired
I reinstalled the sql drivers (pdo_sqlsrv & sqlsrv).
I made a file: sqltest.php:
<?php
$host = "172.20.2.10";
$user = "saWeb";
$password = "PASSWORD";
$dbname="DATA";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
];
try {
$connection = new PDO("sqlsrv:Server=$host,1433; Database=$dbname", $user, $password);
} catch(PDOException $e) {
die("Database connection failed: " . $e->getMessage());
exit;
}
echo"Connection Successful";
?>
The output is: Connection Successful
Another try:
<?php
$serverName = "172.20.2.10";
$connectionOptions = array(
"Database" => "DATA",
"Uid" => "saWeb",
"PWD" => "PASSWORD"
);
$conn = sqlsrv_connect($serverName, $connectionOptions);
$tsql= "SELECT ##Version as SQL_VERSION;";
$getResults= sqlsrv_query($conn, $tsql);
if ($getResults == FALSE)
die(FormatErrors(sqlsrv_errors()));
?>
<h1> Results : </h1>
<?php
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
echo ($row['SQL_VERSION']);
echo ("<br/>");
}
sqlsrv_free_stmt($getResults);
function FormatErrors( $errors )
{
/* Display errors. */
echo "Error information: <br/>";
foreach ( $errors as $error )
{
echo "SQLSTATE: ".$error['SQLSTATE']."<br/>";
echo "Code: ".$error['code']."<br/>";
echo "Message: ".$error['message']."<br/>";
}
}
?>
The output: Microsoft SQL Server 2014 (SP1-GDR) (KB4019091) - 12.0.4237.0 (X64) Jul 5 2017 22:03:42 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.3 (Build 9600: ) (Hypervisor)
I can connect with the SQL Server without Laravel, what's wrong with my Laravel configuration?
You have 2 ips in your tests tests 172.20.2.10 and 127.20.2.10.. Probably a typo and the one you have to set in your .env and config/database.php is 172.20.2.10
login to your main MS database. password and name check. Sometimes a wrong password gets the message Login timeout expired.
laravel:
'host' => '127.20.2.10',
or
'host' => env('DB_HOST'), //env write DB_HOST 127.20.2.10

connection to localhost works but not ip

If I connect to the database using 'localhost' as hostname, It works
$flag = [
'database_host' => 'localhost',
'database_port' => '',
'database_name' => 'dbdemo',
'database_user' => 'userdemo',
'database_password' => 'uijk',
'database_table' => 'tabledemo',
];
$link = mysqli_connect($flag['database_host'],$flag['database_user'],$flag['database_password'],$flag['database_name']);
But when I set up the hostname by using his ip (which I get through echo $_SERVER['SERVER_ADDR'];), It returns the error
Connection refused
I'm confused, is it not basicaly the same thing?

Aws database error php mysql

I have connected my appication with aws rds with the script below:
function db_connect() {
$result = new mysqli($_SERVER['RDS_HOSTNAME'], $_SERVER['RDS_USERNAME'], $_SERVER['RDS_PASSWORD'], $_SERVER['RDS_DB_NAME'], $_SERVER['RDS_PORT']);
if (!$result) {
throw new Exception('Could not connect to database server');
} else {
return $result;
}
}
It was working fine then i had to change it due to a new feature which someone else wrote the code for:
$dbOptions = array(
'db_host' => 'RDS_HOSTNAME',
'db_user' => 'RDS_USERNAME',
'db_pass' => 'RDS_PASSWORD',
'db_name' => 'RDS_DB_NAME'
);
I didn't add the port because he didn't and i never connected to database with an array and key like this, how do i go about adding port like at what position.
I was forgetting the $_SERVER variable:
$dbOptions = array(
'db_host' => $_SERVER['RDS_HOSTNAME'],
'db_user' => $_SERVER['RDS_USERNAME'],
'db_pass' => $_SERVER['RDS_PASSWORD'],
'db_name' => $_SERVER['RDS_DB_NAME']
);

PHP Loop to Access MySQL Databases

I'm trying to figure out how to code a loop in a PHP script that:
gets $hostname, $username $password and $platform from an included script for a bunch of MySQL databases (different remote servers with different access credentials) I just have read-only access to
runs the PHP script on each of the databases
I have all the variables stored in an array that looks like this:
$servers = array(
'server1' => array(
'hostname' => '<serverurl>'
'username' => 'readonly',
'password' => 'pword',
'platform' => 'platform'
),
'server2' => array(
'hostname' => 'serverurl'
'username' => 'readonly',
'password' => 'pword',
'platform' => 'platform'
),
},
I'm having trouble figuring out how to pass those values into a loop statement in my PHP script though - how would I make it run on every server in the array?:
$dbhandle = mysql_connect($hostname, $username, $password) or die(mysql_error('Unable to connect to MySQL'));
echo 'Connected to MySQL<br>';
mysql_select_db($platform, $dbhandle) or die(mysql_error('Unable to connect to database'));
echo 'Connected to database<br>';
Sorry for the noob question/if this is a repeat - I couldn't find anything similar when I searched. Is there a good site for me to look up this sort of thing? Thanks!
<?php
$dbhandles = array();
foreach($servers as $server => $details) {
$dbhandles[$server] = mysql_connect($details['hostname'], $details['username'], $details['password']) or die(mysql_error('Unable to connect to MySQL'));
}

Categories