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

How does php connect to the database?

silencement
Release: 2023-02-25 07:20:01
Original
2388 people have browsed it

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);
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template