Home >Backend Development >PHP Problem >How PHP connects to mysql database

How PHP connects to mysql database

(*-*)浩
(*-*)浩Original
2019-09-18 10:09:053651browse

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.

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=&#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);

After a series of connection operations, we create a sql statement to query and verify the data table.

In the above code, we must first create some variables that need to be used, such as database user name, database name and password, etc. Then we connected the database named php using object-oriented method. Then use the if conditional statement and the connect-error method to determine whether the PHP connection to the database is successful.

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=&#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 PHP connects to mysql 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