Marie03
Marie03

Reputation: 41

SQLSTATE[HY000] [2002] Connection refused (right port)

I would like to print the measured data of my weatherstation on a website. Therefore I would like to connect my MariaDB-database. Here ist my code.

<?php

$username = "root";
$password = "M1lVhPuio";
$database = "weatherbot";

try {
    $pdo = new PDO("mysql:host=raspberrypi;port=3306;database=$database", $username, $password);
    //Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
    die("ERROR: Could not connect. ". $e->getMessage());
}

?>

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title> Wetterstation </title>
    </head>
    <body>
        <h1> Meine Wetterdaten </h1>
        
        
    </body>
</html>

When I open the website, I see this: "ERROR: Could not connect. SQLSTATE[HY000] [2002] Connection refused"

There's already an entry in this forum about this case, but adding the port didn't work for me. (3306 is the right port.)

Upvotes: 1

Views: 3869

Answers (1)

Marie03
Marie03

Reputation: 41

Like Sergio Rinaudo said, I had to use the default address instead of "raspberrypi":

$servername = "127.0.0.1";

try {
    $pdo = new PDO("mysql:host=$servername;port=3306;database=database", root, M1lVhPuio);

Thank you for your help!

Upvotes: 1

Related Questions