php is a scripting language widely used in the field of web development. It is often combined with mysql database and used to develop websites. Tell you how php connects to mysql database.
mysqli connects to the database and pdo connects to the database.
The first method: use mysqli to connect to the mysql database (Recommended learning: PHP programming from entry to proficiency)
## The #MYSQLi function is a new driver method introduced in PHP5.0.0 version. Its function is to operate 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);
Second method: Use PDO to connect to the database
PHP Data Object (PDO) extension defines a lightweight consistent interface for PHP to access the database .
PDO provides a data access abstraction layer, which means that no matter which database is used, the same functions (methods) can be used to query and obtain data.
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 PHP connects to mysql database. For more information, please follow other related articles on the PHP Chinese website!