php 新的 mysqli 与 mysqli_connect
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15707696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
new mysqli vs mysqli_connect
提问by FosAvance
What is difference between the new mysqli
and mysqli_connect
?
I know that executing a query is different;
for example: mysqli->query()
and mysqli_query()
Why are there two different types, what is the need for the difference?
newmysqli
和 和有什么不一样mysqli_connect
?我知道执行查询是不同的;
例如:mysqli->query()
和mysqli_query()
为什么有两种不同的类型,有什么需要区别的?
回答by Hanky Panky
One is for Procedural style programming and other is for OOP style programming. Both serve the same purpose; Open a new connection to the MySQL server
一种用于过程式编程,另一种用于 OOP 式编程。两者都有相同的目的;Open a new connection to the MySQL server
OOP Style usage
OOP 风格用法
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
Procedural Style usage
程序风格的使用
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
Reference: PHP Manual
参考:PHP 手册
回答by Rick Buczynski
Right on @Hanky Panky. I'd also add to that the PHP docs:
就在@Hanky Panky 上。我还要补充一下 PHP 文档:
http://www.php.net/manual/en/mysqli.construct.php
http://www.php.net/manual/en/mysqli.construct.php
Note:
OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.
笔记:
仅限 OO 语法:如果连接失败,仍会返回一个对象。要检查连接是否失败,请使用 mysqli_connect_error() 函数或 mysqli->connect_error 属性,如前面的示例中所示。
So error handling is just one difference.
所以错误处理只是一个区别。
回答by Danial
I just found a subtle but interesting difference between the two.
我刚刚发现了两者之间微妙但有趣的区别。
If you encounter a connection error with mysqli_connect
(like $connection = mysqli_connect()
), no mysql info will be returned to the $connection variable. As such, you will not be able to identify the error with myqli_errno($connection)
.
如果您遇到连接错误mysqli_connect
(如$connection = mysqli_connect()
),则不会向 $connection 变量返回任何 mysql 信息。因此,您将无法通过 识别错误myqli_errno($connection)
。
However if you encounter a connection error using new mysqli (like $connection = new mysqli()
), the mysql info WILL be returned and you can check the error with $connection->connect_errno
.
但是,如果您使用新的 mysqli(如$connection = new mysqli()
)遇到连接错误,将返回 mysql 信息,您可以使用$connection->connect_errno
.
Knowing this, I'd opt for new mysqli.
知道了这一点,我会选择新的 mysqli。
Oops... Just saw answer from Rick Buczynski and realized after posting that I'm restating what he said, but his reply is more informative.
糟糕...刚刚看到 Rick Buczynski 的回答,并在发帖后意识到我在重申他所说的话,但他的回复提供了更多信息。