Home> Topics> php mysql> body text

What is the function method for php to connect to mysql database?

青灯夜游
Release: 2023-01-13 00:42:52
Original
10316 people have browsed it

The function that PHP uses to connect to the mysql database is mysqli_connect(). This function can open a new connection to the MySQL server. The syntax format is "mysqli_connect(hostname, username, password, database, [port], [ socket]);".

What is the function method for php to connect to mysql database?

The operating environment of this tutorial: windows7 system, PHP7.1&&mysql8 version, DELL G3 computer

In PHP, you can use the mysqli_connect extension of mysqli () function to realize the connection to the MySQL database. The function syntax format is as follows:

mysqli_connect(host,username,password,dbname,port,socket);
Copy after login
Parameter Description
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.

Return value: Returns an object representing the connection to the MySQL server.

It should also be noted that the mysqli_connect() function is an alias of the mysqli::__construct() function, and all objects using mysqli() can also be used to connect to the database.

Example: The following is a simple code to connect to the database.

1) Process-oriented writing method

'; print_r($data); ?>
Copy after login

2) Object-oriented writing method

 connect_errno){ die('数据库连接失败:'.$mysql->connect_errno); }else{ $mysql -> set_charset('UTF-8'); // 设置数据库字符集 $sql = 'select * from user'; // SQL 语句 $result = $mysql -> query($sql); $data = $result -> fetch_all(); $mysql -> close(); } echo '
'; print_r($data); ?>
Copy after login

The running results are as follows:

Array ( [0] => Array ( [0] => 1 [1] => 张三 ) )
Copy after login

Recommended learning : "PHP Video Tutorial"

The above is the detailed content of What is the function method for php to connect to mysql 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!