Home > Article > Backend Development > How does php connect to the database?
PHP has two methods to connect to the mysql database: mysqli and pdo.
The first method: use mysqli to connect to the mysql database
The code example is as follows
<?php $host='127.0.0.1'; $user='root'; $password='root'; $dbName='php'; $link=new mysqli($host,$user,$password,$dbName); if ($link->connect_error){ die("连接失败:".$link->connect_error); } $sql="select * from admins"; $res=$link->query($sql); $data=$res->fetch_all(); var_dump($data);
The second method: use PDO to connect to the database
The code example is as follows :
<?php $host='127.0.0.1'; $user='root'; $password='root'; $dbName='php'; $pdo=new PDO("mysql:host=$host;dbname=$dbName",$user,$password); $sql="select * from admins"; $data=$pdo->query($sql)->fetch(); var_dump($data);
The above is the detailed content of How does php connect to the database?. For more information, please follow other related articles on the PHP Chinese website!