user2455869
user2455869

Reputation: 151

Error Connecting to Existing Database with PHP and MySQL

I am tryoing to connect to a mysql database with PHP. My code in the pho file is:

try {
        $pdo = new PDO("mysql:host=localhost;dbname=BurgerBar", 
            "root", "root");
    } catch (PDOException $e) {
        $response = "Failed to connect: ";
        $response .= $e->getMessage();
        die($response);
    }

When I run the code in my browser I get

Failed to connect: SQLSTATE[42000] [1049] Unknown database 'burgerbar'

However when I enter mysql in my terminal logging in as root using password root and run

show databases;

I get

+--------------------+
| Database           |
+--------------------+
| information_schema |
| BurgerBar          |
| mysql              |
| performance_schema |
| test               |
+--------------------+

So it shows it exists in mysql. I am using MAMP and cannot figure this out.

Upvotes: 0

Views: 99

Answers (1)

Len_D
Len_D

Reputation: 1430

You need to change your connection string from localhost to the ip that MAMP uses instead of localhost and add the port that MAMP talks to mysql on. Try this:

$pdo = new PDO("mysql:host=127.0.0.1;port=5432;dbname=BurgerBar"

Upvotes: 1

Related Questions