Home  >  Article  >  Backend Development  >  How does php connect to the database?

How does php connect to the database?

silencement
silencementOriginal
2019-09-26 15:34:292364browse

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=&#39;127.0.0.1&#39;;
$user=&#39;root&#39;;
$password=&#39;root&#39;;
$dbName=&#39;php&#39;;
$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=&#39;127.0.0.1&#39;;
$user=&#39;root&#39;;
$password=&#39;root&#39;;
$dbName=&#39;php&#39;;
$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!

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