无法在我的localhost上连接数据库

时间:2014-05-31 11:47:27

标签: php mysql database connect

我有php脚本:

 <?php

$host     = $_GET['host'];
$username = $_GET['username'];
$pass     = $_GET['pass'];

$con = mysql_connect($host, $username, $pass);
if (!$con) {
    echo 'Connection failed!';
} else {
    echo 'Connected successfully!';
}
mysql_close($con);

?>

在远程服务器上运行,当我执行它并尝试连接到我的PC上的数据库时,我收到错误:

Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on '109.60.110.255' (4) in /home/a6859995/public_html/zavrsni/connect.php on line 12

我该如何解决?

4 个答案:

答案 0 :(得分:1)

我建议像这样使用pdo:

class_config.php:

class class_config {

    public static $db_host = 'localhost';
    public static $db_name = 'yourdbname';
    public static $db_user = 'youruser';
    public static $db_pass = 'yourpass';

}

class_pdo.php:

require_once "class_config.php";
class class_pdo {

    public static function dbFactory() {
        $host = class_config::$db_host;
        if(strpos($host,":") !==false) {
            $parts = explode(":",$host);
            $hostname = "unix_socket=".$parts[1];
        } else {
            $hostname = "host=$host";
        }
        $user = class_config::$db_user;
        $pass = class_config::$db_pass;
        $dbase = class_config::$db_name;        
        $pdo = new PDO("mysql:$hostname;dbname=$dbase", $user, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);        
        return $pdo;
    }
}

在你的脚本中使用它:

require_once("class_pdo.php");

$pdo = class_pdo::dbFactory();

$stmt = $pdo->prepare("SELECT * FROM `tablename` WHERE id = :id ");
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
$stmt->execute();

[...]

答案 1 :(得分:0)

请尝试使用此代码:mysql_connect()已弃用,因此请使用mysqli_connect ...      

$host     = $_GET['host'];
$username = $_GET['username'];
$pass     = $_GET['pass'];
$databae  = $_GET['database'];

$con = mysqli_connect($host, $username, $pass, $database);
if (mysqli_connect_errno()) {
    echo 'Connection failed!';
} else {
    echo 'Connected successfully!';
}
mysql_close($con);

?>

答案 2 :(得分:0)

虽然不推荐使用mysql_connect()但尝试使用PDO ..我只是在mysql_connect中为你演示..

$host     = $_GET['host'];
$username = $_GET['username'];
$pass     = $_GET['pass'];
$database  = $_GET['database'];
$connect=new connect($host,$username,$pass,$database);
class connect{

     function __construct($host,$user,$password,$db_name){

        mysql_connect($host,$user,$password) or die("Connection error");

        mysql_select_db($db_name);

        $error=mysql_error();

        if (!empty($error))

        {

            echo $error;

        }

    }

}

答案 3 :(得分:-1)

感谢大家的帮助。主要问题是MySQL数据库的权限,但是PDO的使用帮助我理解了这些天是如何完成的,抱歉在开始的n00b代码:D