Hàm mysqli real_connect() trong PHP
Ví dụ - Phong cách hướng đối tượng
Mở một kết nối mới tới máy chủ MySQL, với các tùy chọn kết nối bổ sung:
<?php
$mysqli = mysqli_init();
if (!$mysqli) {
die("mysqli_init failed");
}
// Specify connection timeout
$con -> options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
// Specify read options from named file instead of my.cnf
$con ->
options(MYSQLI_READ_DEFAULT_FILE, "myfile.cnf");
$con -> real_connect("localhost","my_user","my_password","my_db");
?>
Nhìn vào ví dụ về phong cách thủ tục ở phía dưới.
Định nghĩa và cách sử dụng
Hàm real_connect() / mysqli_real_connect() mở một kết nối mới đến máy chủ MySQL.
Hàm này khác với connect() ở những điểm sau:
- real_connect() yêu cầu một đối tượng hợp lệ được tạo bởi init()
- real_connect() có thể được sử dụng với options() để đặt các tùy chọn khác nhau cho kết nối
- real_connect() có tham số cờ
Cú pháp
Phong cách hướng đối tượng:
$mysqli ->
real_connect( host, username, password, dbname, port, socket, flag )
Phong cách thủ tục:
mysqli_real_connect( connection, host, username, password, dbname, port, socket, flag )
Giá trị tham số
Parameter | Description |
---|---|
connection | Required. Specifies the MySQL connection to use |
host | Optional. Specifies a host name or an IP address |
username | Optional. Specifies the MySQL username |
password | Optional. Specifies the MySQL password |
dbname | Optional. Specifies the default database to be used |
port | Optional. Specifies the port number to attempt to connect to the MySQL server |
socket | Optional. Specifies the socket or named pipe to be used |
flag | Optional. Specifies different connection options. Possible values:
|
Chi tiết kỹ thuật
Giá trị trả về: | ĐÚNG khi thành công. FALSE khi thất bại |
---|---|
Phiên bản PHP: | 5+ |
Nhật ký thay đổi PHP: | PHP 5.6: Đã thêm cờ MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT |
Ví dụ - Kiểu thủ tục
Mở một kết nối mới tới máy chủ MySQL, với các tùy chọn kết nối bổ sung:
<?php
$con = mysqli_init();
if (!$con) {
die("mysqli_init failed");
}
// Specify connection timeout
mysqli_options($con,
MYSQLI_OPT_CONNECT_TIMEOUT, 10);
// Specify read options from named file instead of my.cnf
mysqli_options($con, MYSQLI_READ_DEFAULT_FILE, "myfile.cnf");
mysqli_real_connect($con,"localhost","my_user","my_password","my_db");
?>
❮ Tham khảo PHP MySQLi