Home  >  Article  >  Backend Development  >  What is the method for php to connect to mysql?

What is the method for php to connect to mysql?

王林
王林Original
2020-07-21 13:33:413592browse

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.

What is the method for php to connect to mysql?

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 = &#39;数据库连接地址&#39;;
	$mysql_username = &#39;数据库用户名&#39;;
	$mysql_password = &#39;数据库管理密码&#39;;
	$mysql_database = &#39;数据库名称&#39;;
	$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[&#39;title&#39;];
	}
	// 释放结果集+关闭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!

Statement:
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
Previous article:How to send emails in phpNext article:How to send emails in php