Reputation: 18521
$stmt = $mysqli->prepare("SELECT id, expire, status, username FROM username WHERE username= ?");
$stmt->bind_param('s', $username);
$stmt->execute();
// Store the result (so you can get the properties, like num_rows)
$stmt->store_result();
// Get the number of rows
$amountOfRows = $stmt->num_rows;
// Bind the result to variables
$stmt->bind_result($id, $expire, $status, $db_username);
// Process the variables
while($stmt->fetch()) {
printf("%d %s %s %s\n", $id, $expire, $status, $db_username);
}
Do I need to add
$stmt->free_result();
What about
$stmt->close();
and
$mysqli->close();
QUESTION 1: I am guessing the answer is yes, but I want to know what each of these three do, so I can have a better understanding of how to use them.
I couldn't find much documentation that described what they do and why they are important.
QUESTION 2: My code run perfectly fine at face value, so what are the benefits to using these? Data Management, performance, security, SQL Injection... ?
Upvotes: 1
Views: 1958
Reputation: 1436
Short answer: not vital.
Long answer: I thought the following commands free up memory:
$stmt->free_result();
$stmt->close();
$mysqli->close();
I wasn't sure, so I tested it.
echo(memory_get_usage()); // returns 226472
$mysqli = new mysqli(/* credentials */);
$stmt = $mysqli->prepare("SELECT id, username FROM members");
$stmt->execute();
$stmt->store_result();
$amountOfRows = $stmt->num_rows;
$stmt->bind_result($id, $username);
while($stmt->fetch()) {
printf("%d %s\n", $id, $username);
}
echo(memory_get_usage()); // now returns 230176 (gained 3704)
$stmt->free_result();
echo(memory_get_usage()); // returns 230176 (lost 0)
$stmt->close();
echo(memory_get_usage()); // returns 229816 (lost 360)
$mysqli->close();
echo(memory_get_usage()); // returns 229720 (lost 96)
$stmt->close()
and $mysqli->close()
actually free up memory, but it is a tiny bit.
Your system won't be any more vulnerable because you choose not to write these two/three lines. They only free up (little) memory. It is arguably better style to include at least $mysqli->close()
in your code, but it's up to you.
Verdict: not vital.
Upvotes: 2