如何在PHP中从服务器连接数据库?

时间:2017-08-30 08:16:24

标签: php mysql

  1. My Source在我的localhost上,DATABASE在我们的服务器上,所以我想要 连接数据库与我的服务器。
  2. 当我尝试连接数据库时,会出现错误“无法连接:无主机路由”。

     $con = mysql_connect("192.168.0.99", "root", "password") or  
     die("Could not connect: " . mysql_error());
    

4 个答案:

答案 0 :(得分:1)

  1. 使用mysqli
  2. 确保您在mysql上拥有GRANT访问权限

    GRANT ALL PRIVILEGES ON *.* TO 'username'@'hostname' 所以在你的情况下你需要给予许可GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.0.99'

  3. 尝试远程连接服务器

  4.  mysql -u root -p -h 192.168.0.99
    Enter password:
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 17
    Server version: 5.0.45 Source distribution
    
    Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
    
    mysql> 
    

答案 1 :(得分:0)

$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

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

答案 2 :(得分:0)

我假设您在连接字符串中输入的IP地址是您计算机的IP地址。

这不起作用的原因可能是因为MySQL服务器配置为仅侦听Localhost环回IP。

所以...以下应该有效:

<?php
$con = mysqli_connect("localhost","root","password");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

注意:我已经改为使用mysqli而不是mysql_connect,因为不再支持。

如果您的本地主机上没有保存数据库服务器,则可能需要检查服务器是否已配置为接受来自您的IP地址的连接。此设置位于my.cnf文件中,名为“bind”。将其更改为0.0.0.0以接受并侦听来自任何IP地址的连接。

答案 3 :(得分:-1)

    const USERNAME="root";
    const PASSWORD="password";
    const HOST="localhost";
    const DB="DBName";

 private function getConnection(){
        $username = self::USERNAME;
        $password = self::PASSWORD;
        $host = self::HOST;
        $db = self::DB;
        $connection = new PDO("mysql:dbname=$db;host=$host", $username, $password);
        return $connection;
    }