One website - multiple database - php

We have multiple masters that are synced into a slave. We have decided to create a database for each master (let say MDB0001; MDB0002; MDB0003, etc...). This will allow to not corrupt the entire database if one replication fails or has corrupted data... The slave is used to show information to the people that are on the web (the master is only available in the local network)
The purpose is: we want to have a website (in php) on the server (slave) that shows the content for each database depending who is logged in. So if the user MDB0001 is connected, we have to read the data from the database MDB0001.
How can this be done? Is it a good way to do that? Or, do I have to duplicate the website for each database?
I hope I'm clear in my explanation. Thanks

assuming you get a variable from the login you could put a key->value array together on your db.php page;
$userDBs = array('login1'=>'db1','login2'=>'db2');
$dbName = $userDBs[$loggedinID]; // if login1 logs in, db1 would be result.
$db = new PDO('mysql:host=localhost;dbname='.$dbName, 'someUser', 'somePass');
or have a seperate db for the associations:
$sel = "Select dbName from databases where userId='".$loggedInID."'";
$stmt = $db->query($sel);
while($r = $stmt->fetch()){
$dbName = $r['dbName'];
}
$db = new PDO('mysql:host=localhost;dbname='.$dbName, 'someUser', 'somePass');

Related

Need idea for Two different remote MYSQL database connection in one PDO

iam developing a multi tenant application. And i need an idea. as iam in a dark tunnel with no light now
there will be two database involve from two different location.
Database (A) - Tenant List with tenant database (B) username,password,IP address
Database (B) - Specific tenant info base on selected tenant from database (A)
What i want to achieve is:
When user enter their web url with specific user_id in url, first it will query the tenant list in Database (A) based on the user_id from url.
then, it will straight make a persistent connection to Database (B) using the credential from query Database (A) result.
hope to get ideas and bring me some lights. thank you!
here is what i had try:
public function func_get_user($id){
$tenant = $this->client_info_func($id); // this is function to get Tenant credential from Database A for using in database B
if (!empty($tenant)) {
$pdo_client = $this->cliend_db_conn($tenant['client_db_name'],$tenant['client_db_username'],$tenant['client_db_pass'],$tenant['client_db_ip']); // this is the function to initiate PDO connection to Database B
$Q = "SELECT user_id,user_name,client_id FROM user WHERE client_id =:id";
$R = $pdo_client->prepare($Q);
$R->bindParam(':id', $id);
$R->execute();
$result = $R->fetch(PDO::FETCH_ASSOC);
return $result;
}else{
echo 'Sorry! you are not allowed tenant';
}
}
You haven't posted any code. But the logic is as follows:
Connect to database A using PDO as normal:
$pdo_db_A = new PDO(... ;dbname='database_A', 'db_A_username', 'db_A_password');
Then run this query on database A:
SELECT username, password FROM database_A_table WHERE user_id = ...
Get your data in PHP variables, such as an array:
$db['username'] = $row['username']; // $row being from the above query
$db['password'] = $row['password'];
Make a separate PDO connection to database B and pass in the details:
$pdo_db_B = new PDO(... ;dbname='database_B', $db['username'], $db['password']);

Is the correct way to connect my website to my server?

I'm a total beginner when it comes to PHP, I have a fair grasp of the syntax but I'm not sure about the safest way to utilise it to connect to my server. I apologise that this is a sort of generic question rather than a code problem, since my code technically works.
I have a .php site doc with a basic comment submission form. The only way I can think of to connect to the server is to allow a "dummy" user with select only privelege to call a stored function to accept the comment.
If my dummy account is called siteuser then am I going round this the right way? This is the section of the PHP that I'm using to connect. I believe this code is only visible server side so nobody can ever see it and use the password or username to connect some other way? Or is there a sort of default string I can use in my php without creating the dummy user, seeing as the php and server is all hosted via the same provider?
$sqlserv = "localhost";
$sqlname = "siteuser";
$sqlpass = "mypassword";
$sqldbdb = "comments_table";
$conn = new mysqli($sqlserv, $sqlname, $sqlpass, $sqldbdb);
What i do is this to connect to my DB
db.php:
<?php
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('/somepath/config.ini');
//Mysqli Connection
$conn = new mysqli($config['host'], $config['user'], $config['pass'], $config['dbname']);
if($conn->connect_errno > 0){
die('Unable to connect to database [' . $conn->connect_error . ']');
//Set encoding
mysqli_set_charset($conn, "utf8") or die;
}
?>
and in config.ini:
[database]
user = johndoe
pass = someweirdpassword
dbname = the_name
host = localhost
both files have 700 permissions, so only user (and no one else can access it)
also the config.ini file is placed somewhere outside the public_html directory, i'm not totally sure if that helps or not but i do it that way.

php connecting to two databases on diff servers and using insert select

hi I need some help what I am trying to do is using insert select statement like this where databases are on diff servers.
insert into db1.copy2 (c1,c2) select c1,c2 from db2.copy2;
db1 is on amazon web service relation database and db2 is on local host(wamp) how can i make a PHP script that can accommodate two databases like that and that will allow me to execute a query like that. this script will execute on local host
thanks..
There are many pieces of software for syncronising or copying data between to database servers, maybe you should use one of those. Otherwise you could just do it in 2 steps
in pseudo code
$sql = "select c1,c2 from db2.copy2";
$Results = pdofetchall($sql);
foreach ($Results as $row){
$c1 = $row['c1'];
$c2 = $row['c2'];
$InsertSQL = "insert into db1.copy2 VALUES($c1,$c2) ";
executesql($InsertSQL);
}
Note this is pseudo code and defintitely cannot be copied and pasted, but give you the gist of what you need to do.
You have 3 options:
If you can connect the 2 servers via a vpn network or ssh connection so that the 2 servers can directly see each other, then you can use federated table engine:
The FEDERATED storage engine lets you access data from a remote MySQL
database without using replication or cluster technology. Querying a
local FEDERATED table automatically pulls the data from the remote
(federated) tables. No data is stored on the local tables.
This solution would enable the syntax you used in the question.
Again, you have to enable direct connection between the 2 servers and you set up replication between the 2 servers, essentialky making sure that the data available on the localhost is copied to the amazon server. The query would run on the amazon server and would query the copied data.
You combine data within php from the 2 data sources either by directly connecting to both instances or by setting up a web-based api on local server that can be used to transfer data from the local server to amazon.
you can do this easily if your 2 database on the same server, just make a connection to one database and pass your query easily:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "insert into db1.copy2 (c1,c2) select c1,c2 from db2.copy2;";
this will work for you

Accessing my other database from my website 1 to my website 2

I have website 1 currently uploaded in the web and i have also develop a website 2 running on the localhost for now.. I want to access or get some value from the website 1 database to my website 2..is this possible using php query or javascripting? if not, what approach i need to take? thanks for the help
Yes you can, You have to just pass the parameters of the server details like this example.
<?php
//Connect To Database
$hostname='ukld.db.5510597.hostedresource.com';
$username='myusername';
$password='mypassword';
$dbname='testdb';
//your rest of code
?>
To allow connections from an external IP-address, you will need to do the following as well:
Grant access to a new database
If you want to add a new database called foo for user bar and remote IP 202.54.10.20 then you >need to type the following commands at mysql> prompt:
mysql> CREATE DATABASE foo;
mysql> GRANT ALL ON foo.* TO bar#'202.54.10.20' IDENTIFIED BY 'PASSWORD';
More information
Yes, It's simple.
<?php
$hostname = "remote_host_name";
$database = "remote_database_name";
$username = "database_username";
$password = "database_password";
$con = mysql_connect($hostname, $username, $password);
mysql_select_db($database, $con);
?>
Use this $con as the second parameter while running query.
e.g. mysql_query($query, $con);
Make sure that you have granted the access of server 1 in server 2 mysql database.

Connecting to 3rd party database in Joomla?

I need to connect to another database in Joomla! that's on another server. This is for a plugin and I need to pull some data from a table.
Now what I don't want is to use this database to run Joomla!, I already have Joomla! installed and running on its own database on its server but I want to connect to another database (ON TOP of the current one) to pull some data, then disconnect from that 3rd party database - all while keeping the original Joomla database connection in tact.
You can connect to an external database from your joomla instance without using the current ressource of your joomla DB.
Try this:
<?php
$option = array(); //prevent problems
$option['driver'] = 'mysql';
$option['host'] = 'dbase.host.com';
$option['user'] = 'login';
$option['password'] = 'pwd';
$option['database'] = 'anotherdb';
$db = & JDatabase::getInstance( $option );
?>
For more infromations regarding this, check the Joomla! Documentation
I had same problem before. Fond a good tutorial showing how to connect to multiple database and switch back and forth, it also has sample code. It explains how to connect to multiple (internal and external) databases factory style, without creating multiple connections per request. This means that if you create database instance in controller same connection will be used in the model. Improves performance.
Another good explanation is on Joomla Documentation site [http://docs.joomla.org/How_to_connect_to_an_external_database].
Can you create a generic mysql-php conection inside your plugin code to create a connection ?
like
mysql_connect("remot_server_ip:3306","user","pass");
mysql_select_db("your database");
//code goes here
:
:
:
mysql_close(connection);

Categories