在PHP中,mysqli_connect()
函数用于建立与MySQL数据库的连接。以下是mysqli_connect()
函数的语法:
| mysqli_connect(string$hostname [, string$username [, string$password [, bool$new_link = false [, int$client_flags = 0 ]]]]) |
参数说明:
$hostname
:要连接的MySQL服务器的主机名或IP地址。
$username
:可选参数,用于提供连接数据库的用户名。如果省略该参数,则使用当前有效的用户名。
$password
:可选参数,用于提供连接数据库的密码。如果省略该参数,则没有密码连接数据库。
$new_link
:可选参数,设置为true
表示创建一个新的连接,如果设置为false
(默认值),则表示使用现有的连接。
$client_flags
:可选参数,用于指定连接的标志。通常将其设置为0(默认值)。
示例用法:
| $hostname = "localhost"; |
| $username = "your_username"; |
| $password = "your_password"; |
|
|
| |
| $connection = mysqli_connect($hostname, $username, $password); |
|
|
| if (!$connection) { |
| die("连接失败: " . mysqli_connect_error()); |
| } |
|
|
| echo"连接成功!"; |
在上面的示例中,我们提供了主机名、用户名和密码来建立与MySQL数据库的连接。如果连接成功,将输出"连接成功!"。如果连接失败,将输出"连接失败: "以及错误信息。
请注意,上述示例中使用的是mysqli_connect()
函数,它是旧版本的MySQLi扩展函数。在新版本的PHP中,推荐使用mysqli_init()
和mysqli_connect_errno()
等函数来实现数据库连接。另外,还可以使用PDO扩展来简化数据库连接的过程。
http://www.51relaw.com/news/bencandy.php?&fid=12&id=78876