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