Note with Francis' example, using the function name link() will throw an error at runtime as it is already a function within the language. see: http://php.net/manual/en/function.link.php
(PHP 5, PHP 7)
mysqli::close -- mysqli_close — 事前にオープンしているデータベース接続を閉じる
オブジェクト指向型
手続き型
既に開いているデータベース接続を閉じます。
既に開いている、持続的でない MySQL 接続と、 結果セットはオブジェクトが破棄されるとすぐに閉じられます。 既に開いている接続と結果セットを明示的に閉じるのはオプションですが、 データベースから結果を取得した後、大量に処理が残っている場合、 データベースに関する処理を全て実行し終わったらすぐに接続を閉じるのが望ましいです。
成功した場合に true
を、失敗した場合に false
を返します。
例1 mysqli::close() example
オブジェクト指向型
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$result = $mysqli->query("SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
/* 不要になったらすぐに、接続を閉じます */
$mysqli->close();
foreach ($result as $row) {
/* データベースから取得したデータを処理します */
}
手続き型
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$result = mysqli_query($mysqli, "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");
/* 不要になったらすぐに、接続を閉じます */
mysqli_close($mysqli);
foreach ($result as $row) {
/* データベースから取得したデータを処理します */
}
注意:
mysqli_close() は、持続的な接続を閉じません。 詳細な情報は、マニュアルの 持続的データベース接続を参照ください。
Note with Francis' example, using the function name link() will throw an error at runtime as it is already a function within the language. see: http://php.net/manual/en/function.link.php
Since a lot of manual examples recommend to use a variable to initiate your connection, it is interesting to know that mysqli_close() will unset that variable, causing further connection attempts to fail.
ex:
$link = mysqli_connect($host, $user, $pw);
if ($link) {
// Database is reachable
mysqli_close($link);
}
if ($link) {
// Database unreachable because $link = NULL
}
Easiest solution for me is to initiate connection through a function.
ex:
function link() {
global $host;
global $user;
global $pw;
global $link;
$link = mysqli_connect($host, $user, $pw);
}
link();
// Database is reachable
mysqli_close($link)
link();
// Database is reachable
mysqli_close($link)
I've had situations where database connections appeared to persist following php execution. So, now, my __destructor function explicitly contains a $cxn->close(). It hurts nothing, and helps avoid memory leaks.