Home  >  Article  >  Database  >  Detailed explanation of PDO connection database and DSN

Detailed explanation of PDO connection database and DSN

黄舟
黄舟Original
2017-02-25 10:30:511977browse

PDO constructor

In PDO, to establish a connection with the database, you need to instantiate the PDO constructor. The syntax of the PDO constructor is as follows:

__construct(string $dsn[,string $username[,string $password[,array $driver_options]]])

The parameters are described as follows

dsn: data source name, Include hostname, port number and database name.

username: username to connect to the database

password: password to connect to the database

driver_options: other options for connecting to the database

For example:

$dbms='mysql';
$dbName='admin';
$user='root';
$pwd='password';
$host='localhost';
$dsn="$dbms:host=$host;dbname=$dbName";
try{
    $pdo=new PDO($dsn,$user,$pwd);
    echo "PDO连接MySQL成功";
}catch(Exception $e){
    echo $e->getMessage().&#39;<br>&#39;;
}

The running result is:

PDO连接MySQL成功

If any of the above fields are filled in incorrectly, an exception will be thrown through the try catch statement

DSN detailed explanation

DSN is the abbreviation of Data Source Name. DSN provides the information needed to connect to the database. The DSN of PDO includes 3 parts: PDO driver name (such as: 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, so the host name in the DSN needs to be modified.

Since the database server only listens for connection requests 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 PHP cannot find the port number of 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";

In addition, since a database server may have multiple databases, when connecting to the database through DSN, the database name is usually included, so as to ensure the connection

is the database that the user wants, not other databases.

The above is the detailed explanation of PDO connection database and DSN. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn