简体   繁体   中英

I can not connect with PHP PDO

In my PHP apicación I connect to a MySQL database with PDO, but I'm having the following problem, the error message;

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]

The code to access the database is:

    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;
    }

What I find strange is that the same parameters to connect to "mysqli" I have no problems and I connect successfully, run CRUD statements and no problems, the code is as follows;

The code

    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;
    }

Well, I need to connect with PDO but I can not find the solution , waiting for suggestions or help!

Sorry, can not find in the forum how to respond with a picture, but is this;

solve my problem, change the port from 3307-3306 (3306 was the port that went out in error) of USBWebserver. now work!

在此处输入图片说明

note: above the port was 3307

solve my problem, change the port from 3307-3306 (3306 was the port that went out in error) of USBWebserver. now work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM