PHP 8.4.2 Released!

面向过程和面向对象,两种接口

mysqli 扩展具有双重接口。支持面向过程和面向对象,两种编程范式。

从旧的 mysql 扩展迁移的用户可能更喜欢过程接口。过程接口类似于旧的 mysql 扩展。在许多情况下,函数名称仅在前缀上有所不同。一些 mysqli 函数将连接句柄作为第一个参数,而匹配的旧 mysql 接口函数将其作为可选的最后一个参数。

示例 #1 从旧的 mysql 扩展轻松迁移

<?php
$mysqli
= mysqli_connect("example.com", "user", "password", "database");
$result = mysqli_query($mysqli, "SELECT 'Please do not use the deprecated mysql extension for new development. ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($result);
echo
$row['_msg'];

$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$result = mysql_query("SELECT 'Use the mysqli extension instead.' AS _msg FROM DUAL", $mysql);
$row = mysql_fetch_assoc($result);
echo
$row['_msg'];

以上示例会输出:

Please do not use the deprecated mysql extension for new development. Use the mysqli extension instead.

面向对象接口

除了经典的过程式接口,用户还可以选择使用面向对象接口。文档是使用面向对象的接口组织的。面向对象的接口按用途分组进行展示函数,使其更容易上手。参考部分提供了两种语法变体的示例。

这两个接口之间没有显着的性能差异。用户可以根据个人喜好进行选择。

示例 #2 面向对象和面向过程接口

<?php

$mysqli
= mysqli_connect("example.com", "user", "password", "database");

$result = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($result);
echo
$row['_msg'];

$mysqli = new mysqli("example.com", "user", "password", "database");

$result = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");
$row = $result->fetch_assoc();
echo
$row['_msg'];

以上示例会输出:

A world full of choices to please everybody.

面向对象的接口用于快速入门,因为参考部分是以这种方式组织的。

混合风格

可以随时在样式之间切换。出于代码清晰度和编码风格的原因,这两种风格不建议混合使用。

示例 #3 糟糕的编码风格

<?php

$mysqli
= new mysqli("example.com", "user", "password", "database");

$result = mysqli_query($mysqli, "SELECT 'Possible but bad style.' AS _msg FROM DUAL");

if (
$row = $result->fetch_assoc()) {
echo
$row['_msg'];
}

以上示例会输出:

Possible but bad style.

参见

添加备注

用户贡献的备注 1 note

up
30
Anonymous
9 years ago
Just want to add that both procedural mysqli_connect_errno and mysqli_connect_error DON'T accept any arguments!
http://php.net/manual/de/mysqli.connect-errno.php
http://php.net/manual/de/mysqli.connect-error.php
"int mysqli_connect_errno ( void )"
"string mysqli_connect_error ( void )"
It clearly states "void" there.

Adding the mysqli-Instance as a parameter makes it look like it pulls the error-number out of the provided instance, which is not actually happening. This could end in a hard to detect bug when connecting to multiple SQL servers.
And it is confusing for beginners.
To Top