ideasia
ideasia

Reputation: 3

Database on other Server (MySQL )

i got a problem while coding my website. I already researched a lot but i really dont know what to do.

function getDB() {
$dbHost = 'otherserver';
$db     = 'database';
$dbUser = 'user';
$dbPass = 'blibla';

$db = new PDO("mysql:host=$dbHost;dbname=$db;charset=utf8mb4", $dbUser, $dbPass);
return $db; }

I dont why, but if I try it with localhost it works. If I change my ($dbHost = '123.123.123') MySQL server it dosent. Why? I really got no idea. Please help me.

Upvotes: 0

Views: 134

Answers (3)

RiggsFolly
RiggsFolly

Reputation: 94662

If you add some error checking to your code, it is quite likely you will get some information that will help you diagnose this problem or at least get an error message that would help someone here understand exactly what is wrong.

So change your code like this and it should generate you a usable error message, when connection is an issue

function getDB() 
{
    $dbHost = 'otherserver';
    $dbname = 'database';
    $dbUser = 'user';
    $dbPass = 'blibla';

    try {
        $db = new PDO("mysql:host=$dbHost;dbname=$dbname", $dbUser , $dbPass );

        /*** set the PDO error mode to exception ***/
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8mb4'");

    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
        exit;
    }
    return $db;
}

$con = getDB();

foreach ($con->query('SHOW TABLES') as $row) {
    print_r( $row );
}

Upvotes: 0

Volodymyr Chumak
Volodymyr Chumak

Reputation: 766

On the machine where MySQL is installed you should config remote access. On a linux systems config file located in /etc/my.ini.

Open it and find section [mysqld]. Make sure line skip-networking is commented (or remove line) and add following line:

bind-address = <HERE_YOUR_IP>

Restart MySQL server: /etc/init.d/mysql restart.

And of course grant access to remote IP address.

GRANT ALL ON user.* TO database@'<HERE_YOUR_IP>' IDENTIFIED BY 'blibla';

More detailed information look here.

Upvotes: 1

Volodymyr Chumak
Volodymyr Chumak

Reputation: 766

You need to create a new MySQL user and grant privileges to allow remote connect to your database.

Something like this:

CREATE USER 'user'@'otherserver' IDENTIFIED BY PASSWORD 'blibla';
GRANT ALL ON *.* TO 'user'@'otherserver';

Upvotes: 1

Related Questions