Joseph Webber
Joseph Webber

Reputation: 2173

When is the earliest I can close my mysqli connection?

Using the below example, when is the earliest the connection can be closed without loss of data?
Normally I do it after setting local variables to the bound results, is this the earliest?

I know it doesn't really matter since the connection is closed when the script finishes, I'm just curious to know when the connection isn't being used anymore.

$conn = new mysqli($host, $user, $password, $database) or die('Error ' . mysqli_error($link));

$userID = json_decode(file_get_contents('php://input'), true)["userID"];

$sql = "SELECT name
          FROM users
         WHERE id = ?";

$stmt = mysqli_prepare($conn, $sql);

if ($stmt) {
  mysqli_stmt_bind_param($stmt, 'i', $userID);

  if (mysqli_stmt_execute($stmt)) {
    mysqli_stmt_store_result($stmt);
    // here?

    if (mysqli_stmt_num_rows($stmt) > 0) {
      mysqli_stmt_bind_result($stmt, $_name);
      // here?
      mysqli_stmt_fetch($stmt);
      // here?
      $name = $_name;

      mysqli_stmt_close($stmt); // Where I currently close it

      if (!empty($name)) {
        echo '{"name": ' . $name . '}';
      } else {
        echo '{"name": "Anonymous" }';
      }

    }
  }
}

Upvotes: 1

Views: 28

Answers (1)

Samir Selia
Samir Selia

Reputation: 7065

The connection should be closed when it's no longer needed or no other mysqli functions will be executed.

In your case it can be closed just after mysqli_stmt_fetch($stmt); since after this you don't need it.

Upvotes: 1

Related Questions