PHP mysqli_real_connect() 函式



定義和用法

mysqli_real_connect() 函式建立與 MySQL 伺服器的連線,並將連線作為物件返回。它與 mysql_connect() 函式的區別在於它接受由 mysqli_init() 函式建立的物件,並且您可以使用 mysqli_options() 函式設定連線的其他選項。

語法

mysqli_real_connect($con,[$host, $username, $passwd, $dname, $port, $socket, $flags] )

引數

序號 引數 & 描述
1

con(可選)

表示與 MySQL 伺服器連線的物件。

2

host(可選)

表示主機名或 IP 地址。如果為此引數傳遞 Nulllocalhost,則本地主機被視為主機。

3

username(可選)

表示 MySQL 中的使用者名稱。

4

passwd(可選)

表示給定使用者的密碼。

5

dname(可選)

表示應在其中執行查詢的預設資料庫。

6

port(可選)

表示要建立與 MySQL 伺服器連線的埠號。

7

socket(可選)

表示要使用的套接字。

8

flags(可選)

表示不同連線選項的整數值,可以是以下常量之一:

  • MYSQLI_CLIENT_COMPRESS

  • MYSQLI_CLIENT_FOUND_ROWS

  • MYSQLI_CLIENT_IGNORE_SPACE

  • MYSQLI_CLIENT_INTERACTIVE

  • MYSQLI_CLIENT_SSL

  • MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT

返回值

此函式返回布林值,如果連線成功則為 true,失敗則為 false

PHP 版本

此函式首次在 PHP 5 版本中引入,並在所有後續版本中均有效。

示例

以下示例演示了 mysqli_real_connect() 函式的用法(過程式風格):

<?php
   $db = mysqli_init();
   //Creating the connection
   $con = mysqli_real_connect($db, "localhost","root","password","test");
   if($con){
      print("Connection Established Successfully");
   }else{
      print("Connection Failed ");
   }
?>

這將產生以下結果:

Connection Established Successfully

示例

在面向物件風格中,此函式的語法為 $con->real_connect(); 以下是此函式在面向物件風格中的示例:

<?php
   $db = mysqli_init();
   //Connecting to the database
   $con = $db->real_connect("localhost","root","password","test");

   if($con){
      print("Connection Established Successfully");
   }else{
      print("Connection Failed ");
   }
?>

這將產生以下結果:

Connection Established Successfully

示例

<?php
   $connection_mysql = mysqli_init();
   
   if (!$connection_mysql){
      die("mysqli_init failed");
   }
   
   if (!mysqli_real_connect($connection_mysql,"localhost","root","password","mydb")){
      die("Connect Error: " . mysqli_connect_error());
   }else{
	  echo "Connection was successful";
   }
   mysqli_close($connection_mysql);
?>

這將產生以下結果:

Connection was successful
php_function_reference.htm
廣告