Ok, so I have easily 100-200 queries on my website now, all parameterised.
Here's an example of one of them:
$mysqli = new mysqli('localhost', 'user', 'password', 'db_name');
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$stmt = $mysqli->prepare("SELECT `x` FROM `y` WHERE `z` = ?");
$stmt->bind_param("s", $test);
$stmt->execute();
$stmt->store_result();
$stmt->close();
$mysqli->close();
So my question is, what is the best practice for opening/closing the connection to the database?
Is it best to leave the connection open, run multiple queries and then close the connection at the end of the page. Like so:
$mysqli = new mysqli('localhost', 'user', 'password', 'db_name');
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$stmt = $mysqli->prepare("SELECT `a` FROM `b` WHERE `c` = ?");
$stmt->bind_param("s", $test1);
$stmt->execute();
$stmt->store_result();
$stmt->close();
$stmt = $mysqli->prepare("SELECT `x` FROM `y` WHERE `z` = ?");
$stmt->bind_param("s", $test2);
$stmt->execute();
$stmt->store_result();
$stmt->close();
$mysqli->close();
Or is it best to open the connection before each query, and then close immediately afterwards? Like so:
$mysqli = new mysqli('localhost', 'user', 'password', 'db_name');
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$stmt = $mysqli->prepare("SELECT `a` FROM `b` WHERE `c` = ?");
$stmt->bind_param("s", $test1);
$stmt->execute();
$stmt->store_result();
$stmt->close();
$mysqli->close();
$mysqli = new mysqli('localhost', 'user', 'password', 'db_name');
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$stmt = $mysqli->prepare("SELECT `x` FROM `y` WHERE `z` = ?");
$stmt->bind_param("s", $test2);
$stmt->execute();
$stmt->store_result();
$stmt->close();
$mysqli->close();
Currently I open the connection before the page opening <html>
tag and then close it just after the closing </html>
tag. Is this safe/good practice?