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
<?php $host = 'localhost'; $username = 'root'; $password = 'root'; $dbname = 'test'; $port = '3306'; $link = @mysqli_connect($host,$username,$password,$dbname,$port); // 连接到数据库 if($link){ mysqli_set_charset($link,'UTF-8'); // 设置数据库字符集 $sql = 'select * from user'; // SQL 语句 $result = mysqli_query($link, $sql); // 执行 SQL 语句,并返回结果 $data = mysqli_fetch_all($result); // 从结果集中获取所有数据 mysqli_close($link); }else{ die('数据库连接失败!'); } echo '<pre class="brush:php;toolbar:false">'; print_r($data); ?>
2) Object-oriented writing method
<?php $host = 'localhost'; $username = 'root'; $password = 'root'; $dbname = 'test'; $mysql = new Mysqli($host, $username, $password, $dbname); if($mysql -> 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 '<pre class="brush:php;toolbar:false">'; print_r($data); ?>
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!