Home >Backend Development >PHP Problem >How to access mysql database in php?

How to access mysql database in php?

青灯夜游
青灯夜游Original
2020-09-30 14:40:588389browse

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 .

How to access mysql database in php?

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

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

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!

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
Previous article:PHP Session loss problemNext article:PHP Session loss problem