Home > database >  Connect to MySQL table using PHP (XAMPP)
Connect to MySQL table using PHP (XAMPP)

Time:01-28

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

CodePudding user response:

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

CodePudding user response:

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);
  •  Tags:  
  • Related