如何连接到外部ip上的数据库?

如何连接到外部ip上的数据库?

问题描述:

I would like to connect to a database with an external ip of the pc on which the server, for example:

<? $db_host = "xxx.xxx.xxx.xxx" //external ip
$db_user = "user"; $db_password = "password"; $db_database = "database"; 
$conn = "mysql:host=$db_host;dbname=$db_database;charset=utf8mb4"; try {$db = new PDO($conn , "$db_user", "$db_password");}catch(PDOException $e) {echo 'Error: '.$e->getMessage();}?>

So, can you do that? And if so, how can I do it? Thanks everyone for help;)

P.s: Sorry for my bad English

First Check Your Public IP Address [ Public Ip Means External Ip Address] From Here : https://www.whatismyip.com/

And Now Check Your System Ip Address ( Internal Ip Address using ipconfig in cmd )

Both Are Differect So You Need To Used Public Ip Address Which One You Get From https://www.whatismyip.com

Now, you have to Give Access permission to Database for Specific iP Address, By Default Mysql is not allowing to Access it SO You Need To Fire This Command for .

Like This :

SQL> GRANT ALL PRIVILEGES ON database.* TO 'user'@'your_database_pc_public_ip' IDENTIFIED BY 'newpassword';

Example::

 SQL> GRANT ALL PRIVILEGES ON database.* TO 'any_name'@'public_ip' IDENTIFIED BY 'any_password';

Then Its Work Fine For You :)

It is very easy to connect remote MySQL Server Using PHP, what you have to do is:

  1. Create a MySQL User in remote server.

  2. Give Full privilege to the User:

    • firewall of the server must be set-up to enable incomming connections on port 3306
    • you must have a user in MySQL who is allowed to connect from % (any host) (see manual for details)
  3. Connect to the Server using PHP Code (Sample Given Below)

$link = mysql_connect('your_my_sql_servername or IP Address', 'new_user_which_u_created', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';

mysql_select_db('sandsbtob',$link) or die ("could not open db".mysql_error());
// we connect to localhost at port 3306

 <?php
   $dbServerName = "DNS Name  or  ip address";
   $dbUsername = "username";
   $dbPassword = "password";
   $dbName = "dbname";

   // create connection
   $conn = new mysqli($dbServerName, $dbUsername, $dbPassword, $dbName);

   // check connection
   if ($conn->connect_error) 
   {
         die("Connection failed: " . $conn->connect_error);
   }
   echo "Connected successfully";
 ?>