我对连接到数据库的效率感兴趣,我是否应该在每个if条件下重新连接到数据库:
if(a > b)
{
connect to database(mysqli_connect(...,....))
do some stuff
close connection to database
}
if(c == d)
{
connect to database(mysqli_connect(...,....))
do some stuff
close connection to database
}
或者以这种方式提高效率:
connect to database(mysqli_connect(...,....))
if(a > b)
{
do some stuff
}
if(c == d)
{
do some stuff
}
close connection to database
答案 0 :(得分:0)
您应该只打开连接1次,最好只在需要时打开。
$connection = null;
function connect()
{
if(is_null($connection)) {
$connection = (mysqli_connect(...,....))
}
return $connection;
}
if(a > b)
{
connect();
do some stuff
}
if(c == d)
{
connect();
do some stuff
}
if($connection)
close connection to database