Home >Backend Development >PHP Problem >How to access mysql database in php?
Methods to access the mysql database in php: 1. Use mysqli_connect() to connect to the mysql database for access; 2. Use mysqli() to connect to the mysql database for access; 3. Use PDO to connect to the database for access .
Recommended: "PHP Video Tutorial"
#How to access the mysql database in php :
Method 1: Use mysqli_connect() to connect to the mysql database for access
mysqli_connect() function opens a new connection to the MySQL server connect.
Syntax
mysqli_connect(host,username,password,dbname,port,socket);
Parameters:
host Optional. Specify the hostname or IP address.
username Optional. Specifies the MySQL username.
password Optional. Specifies the MySQL password.
dbname Optional. Specifies the database to use by default.
port Optional. Specifies the port number to attempt to connect to the MySQL server.
socket Optional. Specifies the socket or named pipe to use.
Example:
<?php $con=mysqli_connect("localhost","wrong_user","my_password","my_db"); // 检查连接 if (!$con) { die("连接错误: " . mysqli_connect_error()); } ?>
Method 2: Use mysqli() to connect to the mysql database
MYSQLi function is in PHP5.0.0 A new driver method was introduced in this version, and its function is to operate the MYSQL database.
<?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);
Method 3: Use PDO to connect to the database
The 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.
Code examples are 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);
Related recommendations: php training
The above is the detailed content of How to access mysql database in php?. For more information, please follow other related articles on the PHP Chinese website!