-1

Is it necessary to close the prepared statement in php by using $stmt->close();

 <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();
?> 
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • In this case, not really since PHP will clean it up for you anyway at the end of the script, but on the other hand, it doesn't hurt to have it either (if something unexpected happens so the PHP process hangs or what ever, which I've never experiences tbh). Does it cause you any issues? – M. Eriksson Jul 10 '21 at 12:02
  • No, it's never necessary to close the statement or the connection. PHP will do it for you. This method should almost never be used. – Dharman Jul 10 '21 at 12:25

1 Answers1

-1

php_mysqli library was written in low level languages which requires manual memory management. Whenever you allocate a new resource it takes some memory from the device RAM to host the allocated data.

Closing allocated resource free's that memory that later could be again used for another allocation requests or lets Operation System to give that part of memory to another programs when needed.

In short: if you want to make your code memory efficient you might want to close resources you've allocated previously. If you don't really care about the efficiency you might not close the resources.


Another think to keep in mind that Operation System also frees allocated memory chunks whenever a program completes execution. So, closing resources manually might not make a noticable improvement in some situations.

References:

TheMisir
  • 4,083
  • 1
  • 27
  • 37