好的,所以现在我的网站上有 100-200 个查询,全部参数化。
这是其中之一的示例:
$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();
所以我的问题是,打开/关闭与数据库的连接的最佳做法是什么?
最好让连接保持打开状态,运行多个查询,然后在页面末尾关闭连接。像这样:
$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();
还是最好在每次查询之前打开连接,然后立即关闭?像这样:
$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();
目前我在页面开始标记之前打开连接<html>
,然后在结束标记之后关闭它</html>
。这是安全/良好的做法吗?