PDO ConstructorIn PDO, to establish a connection to a database requires a constructor that instantiates the PDO, the PDO constructor has the following syntax: __construct (String $dsn [, String $username [, String $password [, array $ Driver_options]]) parameter description DSN: Data source name, including host name, port number, and database name. Username: Connection Database user name password: Connection Database Password Driver_options: Additional options for connecting to the database such as:
$dbms = ' MySQL '; $dbName = ' admin '; $user = ' root '; $pwd = ' password '; $host = ' localhost '; $dsn = "$dbms: host= $host;d bname=$ DbName "; try{ $pdo =new PDO ($DSN, $user, $pwd); echo "PDO connected to MySQL success";} catch (Exception $e) { echo $e->getmessage (). ' <br> ';}
The result of the operation is: PDO connection to MySQL succeeded
If the above is filled with errors, an exception is thrown through the try Catch statement
DSN detailedThe DSN is the acronym for the Data Source name (the datasource names). DSN provides the information needed to connect to the database. The DSN for PDO includes 3 parts: PDO driver name (e.g. MySQL, SQLite, or pgsql), colon, and driver-specific syntax. Each database has its own specific driver syntax. In practice, some database servers may not be on the same computer as the Web server, and you need to modify the host names in the DSN. Because the database server listens for connection requests only on a specific port, each database server has a default port number (MySQL is 3306), but the database administrator can modify the port number, so it is possible that PHP cannot find the port number for the database, so you can include the port number in the DSN. For example:
$DSN = "Mysql:host=127.0.0.1;port=3306;dbname=admin";
also, because a database server may have more than one database, the database name is usually included when you connect to the database through a DSN, which ensures that the connected
Is the database that the user wants, not the other database.
PDO Connection database and DSN detailed