Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alb-noah's avatar

about PDO function (lesson 17 PHP beginners series)

in the PHP Beginner Series in the PDO lesson, Jeffrey wrote a code that connects to the database

$dsn="mysql: host=localhost; port=3306; dbname=myapp; charset=utf8mb4;";

$pdo = new PDO($dsn, 'root');

the root passed into the PDO method is meant for the username of the MySQL

My question is how the function knew that this passed argument was meant for the username, not the password.

1 like
3 replies
tykus's avatar

$username is the second argument of the PDO class constructor:

public __construct(
    string $dsn,
    ?string $username = null,
    #[\SensitiveParameter] ?string $password = null,
    ?array $options = null
)

https://www.php.net/manual/en/class.pdo.php

If you are using PHP8. then you can use named arguments to be more explicit:

$dsn="mysql: host=localhost; port=3306; dbname=myapp; charset=utf8mb4;";

$pdo = new PDO(dsn: $dsn, username: 'root');
1 like
vincent15000's avatar

The PDO class can be constructed with other parameters.

$connexion = new PDO($dsn, $user, $password, $options);
LaryAI's avatar
Level 58

In PHP, when you create a new instance of the PDO class, the constructor expects its parameters in a specific order. This is how it knows which argument corresponds to the username and which to the password. The PDO constructor signature is as follows:

public PDO ( string $dsn , string $username = null , string $password = null , array $options = null )

Here's a breakdown of the parameters:

  1. $dsn: The Data Source Name, which contains the information required to connect to the database.
  2. $username: The username for the database connection.
  3. $password: The password for the database connection.
  4. $options: An array of options for the PDO connection.

In your example:

$dsn = "mysql:host=localhost;port=3306;dbname=myapp;charset=utf8mb4;";
$pdo = new PDO($dsn, 'root');
  • The first argument is the $dsn.
  • The second argument 'root' is the $username.

Since you haven't provided a third argument, the $password defaults to null. The PDO constructor uses the order of the arguments to determine which is which, so it knows that 'root' is the username because it is the second argument. If you needed to provide a password, you would add it as the third argument:

$pdo = new PDO($dsn, 'root', 'your_password');

This order is crucial for the PDO constructor to correctly interpret the parameters.

Please or to participate in this conversation.