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]);".
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);
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); ?>
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] => 张三 ) )
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!