The method for php to connect to mysql is: you can use the mysqli_connect() function to connect. This function opens a new connection to the mysql server and returns an object representing the connection to the mysql server.
There are many ways for PHP to connect to the mysql database. Generally, we will use the mysqli_connect() function to connect. Let's introduce this function below.
(Recommended learning: php tutorial)
Function:
mysqli_connect() function opens a new connection to the MySQL server and returns a An object representing a connection to the MySQL server.
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. Specifies the socket or named pipe to use
Code implementation:
<?php $mysql_server_name = '数据库连接地址'; $mysql_username = '数据库用户名'; $mysql_password = '数据库管理密码'; $mysql_database = '数据库名称'; $conn=mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database); //连接数据库 //连接数据库错误提示 if (mysqli_connect_errno($conn)) { die("连接 MySQL 失败: " . mysqli_connect_error()); } mysqli_query($conn,"set names utf8"); //数据库编码格式 // mysqli_set_charset($conn,"utf8");//设置默认客户端字符集。 // mysqli_select_db($conn,$mysql_database); //更改连接的默认数据库 //查询代码 $sql = “select * from table”; $query = mysqli_query($conn,$sql); while($row = mysqli_fetch_array($query)){ echo $row['title']; } // 释放结果集+关闭MySQL数据库连接 mysqli_free_result($result); mysqli_close($conn); ?>
The above is the detailed content of What is the method for php to connect to mysql?. For more information, please follow other related articles on the PHP Chinese website!