Home > Backend Development > PHP Problem > How to connect to database in php

How to connect to database in php

王林
Release: 2023-03-02 15:20:02
Original
8627 people have browsed it

How to connect to the database in php: This can be achieved through the mysqli_connect() function. Function syntax: [mysqli_connect(host, username, password, dbname, port, socket)], the connection identifier is returned after the connection is successful.

How to connect to database in php

#To use a php script to connect to the database, you can use the mysqli_connect() function.

(Recommended tutorial: php tutorial)

Function introduction:

PHP provides the mysqli_connect() function to connect to the database.

This function has 6 parameters, returns the connection ID after successfully connecting to MySQL, and returns FALSE on failure.

Syntax:

mysqli_connect(host, username, password, dbname,port, socket);
Copy after login

Parameter description:

  • host Optional. Specify hostname or IP address

  • username Optional. Specifies MySQL username

  • #password Optional. Specify MySQL password

  • #dbname Optional. Specifies the database to be used by default

  • port Optional. Specifies the port number to attempt to connect to the MySQL server

  • socket Optional. Specify the socket or named pipe to be used

If you want to disconnect from the database, you can use PHP's mysqli_close() function to achieve this.

This function has only one parameter, which is the MySQL connection identifier returned after the mysqli_connect() function successfully creates a connection.

bool mysqli_close ( mysqli $link )
Copy after login

This function closes the non-persistent connection to the MySQL server associated with the specified connection ID. If link_identifier is not specified, the last open connection is closed.

Tip: There is usually no need to use mysqli_close() because the opened non-persistent connection will be automatically closed after the script is executed.

Code implementation:

<?php$dbhost = &#39;localhost&#39;;  // mysql服务器主机地址
$dbuser = &#39;root&#39;;            // mysql用户名
$dbpass = &#39;123456&#39;;          // mysql用户名密码
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ){
    die(&#39;Could not connect: &#39; . mysqli_error());
}
echo &#39;数据库连接成功!&#39;;mysqli_close($conn);
?>
Copy after login

The above is the detailed content of How to connect to database in php. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template