I use the connection to the database to know the users that I have saved and thus use them to validate the login. Is it recommended that for each request (login) there be a connection and a disconnection?
Attached code:
require_once "conn.php";
function validUser(&$error){
if((!isset($_POST['user'])) || (!isset($_POST['pass']))){
$error[0] = "Usuario y/o contraseña incorrectos.";
return null;
}
$user = $_POST['user'];
$pass = $_POST['pass'];
if(($user == '') || ($pass == '')){
$error[0] = "Usuario y/o contraseña incorrectos.";
return null;
}else{
$con = connection();
$sql = "SELECT name FROM usuarios WHERE name = :user AND password = :pass";
$query = $con->prepare($sql);
$query-> bindParam(':user', $user);
$query-> bindParam(':pass', $pass);
$query-> execute();
$contador = $query -> rowCount();
if($contador != 1){
$error[0] = "Usuario y/o contraseña incorrectos.";
return null;
}
$con = null;
return $user;
}
}
Like everything in life: it depends. Not everything is black and white and there is no concrete answer to a question like this. It will depend on many factors such as:
In PHP in particular, unless you define a persistent connection, the connection to the database will be automatically closed at the end of the script, so opening/closing connections multiple times in the life of a page can be overkill: you will slow down the page and consume resources unnecessarily.
But that doesn't mean you shouldn't do it: if your system doesn't need real-time responses and speed isn't a critical factor, the difference between opening/closing multiple connections or keeping one open for the life of the script is going to be almost negligible. .
My recommendation for the case you raise would be: leave it as it is. I think you're trying to prematurely optimize something that you don't know yet if it's going to be a problem. Focus on other parts of the system and if you then see that opening/closing multiple connections is going to create some kind of problem for you (probably not), you can try other options (eg a single scripted connection that needs it or a connection factory).
Quoting Knuth: " The real problem is that programmers spend too much time worrying about efficiency in the wrong places at the wrong times; premature optimization is the root of all (or at least most) evil in programming. "