2013-06-26 143 views
2

在我的PHPapicación中,我使用PDO連接到MySQL數據庫,但出現以下問題,錯誤消息;我無法連接到PHP PDO

Warning: PDO :: __construct() [pdo. - Construct]: [2002] 
"No connection Could be made ​​Actively Because the target machine refused it." 
(trying to connect via tcp ://localhost: 3306) 

Fatal error: Uncaught exception 'Exception' with message 'Connection failed: SQLSTATE [HY000] [2002] 

訪問數據庫的代碼是:

private $db = NULL; 

    const DB_SERVER = "localhost"; 
    const DB_USER = "root"; 
    const DB_PASSWORD = "usbw"; 
    const DB_NAME = "status_poster"; 

    public function __construct() { 
    //**below the error here!!** 
    $dsn = 'mysql:dbname=' . self::DB_NAME . ';host=' . self::DB_SERVER;// 
    //var_dump($dsn); 
    try { 
     $this->db = new PDO($dsn, self::DB_USER, self::DB_PASSWORD); 
    } catch (PDOException $e) { 
     throw new Exception('Connection failed: ' . $e->getMessage()); 
    } 

    return $this->db; 
    } 

我感到奇怪的是,同樣的參數連接到「mysqli的」我沒有問題,我成功地連接,運行CRUD語句和沒問題,代碼如下;

代碼

function getProducts() { 
    $products = array(); 
    $mysqli = new mysqli("localhost", "root", "usbw", "Datos"); 
    if (mysqli_connect_errno()) { 
     printf("Error in conection: %s\n", mysqli_connect_error()); 
     exit(); 
    } 
    $query = "SELECT Id,sku,name,price FROM products"; 
    if ($result = $mysqli->query($query)) { 
     while ($obj = mysqli_fetch_object($result)) { 
     //instructions... 
     } 
    } 
    $mysqli->close(); 
    return $products; 
    } 

好吧,我需要與PDO連接,但我不能找到解決辦法, 等待建議或幫助!

對不起,在論壇中找不到圖片迴應,但是這是;

解決我的問題,改變端口從3307-3306(3306是出錯的端口)的USBWebserver。現在工作!

enter image description here

注:以上端口是3307

+2

嘗試'127.0.0.1',而不是'萬一localhost'的IPv6被絆倒你。 –

+0

嗨!,試試這個:const db_server =「127.0.0.1」,仍然是錯誤! – MauricioHz

+2

解決我的問題,將端口從3307-3306(3306是出錯的端口)更改爲USBWebserver。現在工作! – MauricioHz

回答

1

解決我的問題,端口從3307-3306改變(3306是錯誤出去的端口)USBWebserver的。現在工作!

+0

謝謝:D太棒了 –