PHP Loop to Access MySQL Databases - php

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'));
}

Related

sqlsrv_connect works fine in php but fails in laravel on the same server(AWS EC2 Instance)

I am trying to connect MSSQL database as my second database in Laravel, In the core PHP file It works fine but when I try to connect in the laravel It throws an error.
Here is my .env
MSSQL_CONNECTION=sqlsrv
MSSQL_DATABASE_URL='/EC2AMAZ-61LPEGK\SQLEXPRESS'
MSSQL_HOST=XX.XX.X.XXX
MSSQL_PORT=1433
MSSQL_DATABASE="/dbcrm"
MSSQL_USERNAME="sauser"
MSSQL_PASSWORD='dbpassword123'
MSSQL_TRUSTSERVER='yes'
MSSQL_ENCRYPT=False
MSSQL_STRICT=false
and here is my laravel database config:
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('MSSQL_DATABASE', '/EC2AMAZ-61LPEGK\SQLEXPRESS'),
'host' => env('MSSQL_HOST', 'XX.XX.X.XXX'),
'port' => env('MSSQL_HOSTDB_PORT', '1433'), //I had tried null
'database' => env('MSSQL_DATABASE', '/dbcrm'), //tried without '/'
'username' => env('MSSQL_USERNAME', 'sauser'),
'password' => env('MSSQL_PASSWORD', 'dbpassword123'),
'trust_server_certificate' => env('MSSQL_TRUSTSERVER', 'yes'), //tried 'no'
'encrypt' => env('MSSQL_ENCRYPT', False), //tried true
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
],
Here is the PHP file code which works fine and connect the database as well as execute the query,
$host ="XX.XX.X.XXX";
$username ="sauser";
$password ="dbpassword123";
$database ="dbcrm";
$params = [
"UID" => $username,
"PWD" => $password,
"Database" => $database,
"TrustServerCertificate" => "yes",
];
if(sqlsrv_connect($host, $params)) {
echo "connected..";
} else {
echo "Connection could not be established.<br />";
echo "<pre>";
die( print_r( sqlsrv_errors(), true));
echo "</pre>";
}
I am using the same server for both cases and I have installed/enabled SQLSRV. Please find the phpinfo screenshots for reference.
Why it is working in PHP file but not in the Laravel. Please help.
Note : MSSQL database is installed on another AWS windows Instance and TCP is enabled, and port number is 1433
Here is the error what I am getting,
Finally, able to figure out the issue, Posting the same so it will help someone who has struck for days and ripping their hair out to find the solution.
Change the below .env variables and database config as below,
MSSQL_ENCRYPT=yes
MSSQL_TRUSTSERVER=True
config/database.php
'trust_server_certificate' => env('MSSQL_TRUSTSERVER', true), //Some libraries accessing ODBC/JBDC require Yes/No settings, others True/False,
'encrypt' => env('MSSQL_ENCRYPT', 'yes'), //same here try Yes/No or True/False

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?

Is it possible to convert a connection object to an array in PHP

I'm wondering if it's possible to convert a database connection object to an array in PHP? I've been researching, it seems you can cast an object as an array, but it doesn't seem to work for a connection object. Here's my script:
<?php
$dbHost="host";
$dbUser="user";
$dbPass="";
$dbName="root";
$dbConn = mysqli_connect($dbHost,$dbUser,$dbPass,$dbName);
$dbParts = (array) $dbConn;
for ($i=0;$i <=3; $i++){
echo $dbParts[$i];
}
?>
Any help would be greatly appreciated!
**[EDIT]**Why I need to access the db connection as an array is because I need to be able to call certain urls in a script, based on what database I'm connected to, as each environment has a different database.
Build your own array:
$db['localhost'] = array('host' => 'localhost',
'user' => 'root',
'pass' => '****',
'name' => 'database1');
Then if needed add the connection to it:
$db['localhost']['conn'] = mysqli_connect($db['localhost']['host'],
$db['localhost']['user'],
$db['localhost']['pass'],
$db['localhost']['name']);
Other possibilities depending on your needs; define the database as the lookup key:
$db['database1'] = array('host' => 'localhost',
'user' => 'root',
'pass' => '****',
'name' => 'database1');
Or define the environment:
$db['production'] = array('host' => 'localhost',
'user' => 'root',
'pass' => '****',
'name' => 'database1');
Well after a little digging I found this ( Tested ).
It relies on you having access to $dbConn.
You can get the database name being used, using something like...
$result=mysqli_query($dbConn,'SELECT DATABASE() as dbName');
$rows = mysqli_fetch_assoc($result);
var_dump($rows);
which you'd probably turn into a function to make it useful along the lines of...
function getDatabaseName($databaseConnection){
$result=mysqli_query($databaseConnection,'SELECT DATABASE() as dbName');
$row = mysqli_fetch_assoc($result);
return $row['dbName'];
// var_dump($rows);
}
$currentDatabase = getDatabaseName($dbConn);
echo $currentDatabase;
You'll have to play with this to suit...

ZF2 Zend\Paginator\Adapter\DbSelect on DB2 i Series

Im creating a Zend APIgility application REST service and having a problem with my fetchAll Mapper function.
I'm connecting to an IBM DB2 database running on an i Series server (AS/400) via DB2 Connect on a Windows Application Server.
My Connection is is made in my local.php as such:
return array(
'db' => array(
'driver' => 'IbmDb2',
'database' => $database,
'username' => $user,
'password' => $password,
'hostname' => $host,
'port' => $port,
'driver_options' => array(
'i5_naming' => DB2_I5_NAMING_ON,
'i5_lib' => 'LIBWEB',
),
),
);
The fetchAll() function in my Mapper class is:
public function fetchAll()
{
$select = new Select('WBRESOURCE');
$paginatorAdapter = new DbSelect($select, $this->adapter);
$collection = new ResourcesCollection($paginatorAdapter);
return $collection;
}
When I hit the DbSelect, ZF2 throws the following DB2 Connect error:
"[IBM][CLI Driver][AS] SQL0204N \"*LIBL.WBRESOURCE\" is an undefined name. SQLSTATE=42704"
Im not sure why its using *LIBL (user defined library list), since I defined the library (SCHEMA) to use as LIBWEB in my connection option.
Thanks in advance!
Rob
Try changing this section:
'driver_options' => array(
'i5_naming' => DB2_I5_NAMING_ON,
'i5_lib' => 'LIBWEB',
Change to":
'driver_options' => array(
'i5_naming' => DB2_I5_NAMING_OFF, <=== change
'i5_lib' => 'LIBWEB',
By using DB2_I5_NAMING_OFF, you should get SQL naming mode. The use of DB2 i5 naming mode will result in things like reliance on a job's library list.
See PHP: db2-connect for some info on the parameter.

connecting to alternate database when primary database is down?

$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");

Categories