PHP MySQLi 函数

PHP mysqli::init() / mysqli_init() 函数分配或初始化 MYSQL 对象以与 mysqli_options 一起使用() 和 mysqli_real_connect()。

注意:对任何 mysqli 函数(mysqli_options() 和 mysqli_ssl_set() 除外)的任何后续调用都将失败,直到 mysqli_real_connect( ) 被称为。

语法

//面向对象风格
public mysqli::init()

//面向过程风格
mysqli_init()
  • 1
  • 2
  • 3
  • 4
  • 5

参数

无需参数。

返回值

返回一个对象。

示例:面向对象风格

下面的示例显示mysqli::init()的用法

<?php
$mysqli = mysqli_init();
if (!$mysqli) {
  die('mysqli_init failed');
}

if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
  die('Setting MYSQLI_INIT_COMMAND failed');
}

//指定连接超时
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10)) {
  die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

//建立与数据库的连接
if (!$mysqli->real_connect("localhost", "user", "password", "database")) {
  die('Connect Error: '. mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

//关闭连接
$mysqli->close();
?>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

上述代码的输出将是:

Success... MySQL host info: localhost via TCP/IP
  • 1

示例:扩展 mysqli 类时的面向对象风格

考虑下面的示例在扩展 mysqli 类时使用此方法。

<?php
class acs_mysqli extends mysqli {
  public function __construct($host, $user, $pass, $db) {
    parent::init();

    if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
      die('Setting MYSQLI_INIT_COMMAND failed');
    }

    if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 10)) {
      die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
    }

    if (!parent::real_connect($host, $user, $pass, $db)) {
      die('Connect Error: ' . mysqli_connect_error());
    }
  }
}

//建立与数据库的连接
$db = new acs_mysqli("localhost", "user", "password", "database");

echo 'Success... ' . $db->host_info . "\n";

//关闭连接
$db->close();
?>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

上述代码的输出将是:

Success... MySQL host info: localhost via TCP/IP
  • 1

示例:面向过程风格

下面的示例显示了 mysqli_init() 函数的用法。

<?php
$mysqli = mysqli_init();
if (!$mysqli) {
  die('mysqli_init failed');
}

if (!mysqli_options($mysqli, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
  die('Setting MYSQLI_INIT_COMMAND failed');
}

//指定连接超时
if (!mysqli_options($mysqli, MYSQLI_OPT_CONNECT_TIMEOUT, 10)) {
  die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

//建立与数据库的连接
if (!mysqli_real_connect($mysqli, "localhost", "user", "password", "database")) {
  die('Connect Error: '. mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($mysqli) . "\n";

//关闭连接
mysqli_close($mysqli);
?>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

上述代码的输出将是:

Success... MySQL host info: localhost via TCP/IP
  • 1