skip to Main Content

I am trying to make a CRUD in PHP. Apache and MySQL is still running.

class DB
{
    static private $connection;
    const DB_TYPE = "mysql";
    const DB_HOST = "localhost";
    const DB_NAME = "crud";
    const USER_NAME = "root";
    const USER_PASSWORD = "";

    static public function getConnection()
    {
        if (static::$connection == null) {
            try {
                static::$connection =  new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);
            } catch (Exception $exception) {
                throw new Exception("connection failed");
            }
        }
        return static::$connection;
    }
}

I am running on localhost:3306

phpMyAdmin is up and running

The output is in the picture

output:

enter image description here

2

Answers


  1. I think you forgot spaces and signs in your connection arguments

    That is your syntax :

    new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);
    

    Which give :

    "mysqlhostlocalhostdbnamecrudroot"
    

    This is the syntax from the doc :

    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    
    Login or Signup to reply.
  2. Your PDO invocation looks weird.

    static::$connection =  new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);
    

    The construct for this is new PDO($dsn, $user, $password);

    The dsn has this format:

    mysql:dbname=testdb;host=127.0.0.1;port=3333 then , user then , password
    

    Your dsn section seems wrong, it should be more like this:

    $dsn = 'mysql:dbname='. self::DB_NAME .';host=' . self::DB_HOST ;
    $user = self::USER_NAME;
    $password = self::USER_PASSWORD;
    
    $dbh = new PDO($dsn, $user, $password);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search