Today I come with a very basic question about connection to data base since I do not have some clear concepts and would like to know what is the difference or benefit of connecting to the database using a class or normally.
That is, what would be the difference of this code :
<?php
class conexion {
/**
* Gestiona la conexión con la base de datos
*/
private $dbhost = 'localhost';
private $dbuser = 'nombre usuario';
private $dbpass = 'contraseña';
private $dbname = 'base de datos';
public function conexion () {
/**
* @return object link_id con la conexión
*/
$conn= new mysqli($this->dbhost,$this->dbuser,$this->dbpass,$this->dbname);
if ($conn->connect_error) {
echo "Error de Connexion ($conn->connect_errno)
$conn->connect_error\n";
header('Location: error-conexion.php');
exit;
} else {
return $conn;
}
}
} ?>
just make this code:
<?php
$conn= new mysqli("localhost","root","","DB");
if($conn){
echo"conexion fail";
}else{
echo"conexion success";
}
?>
More than a question, it is a doubt, that is why the first code would be better?
I hope you can clarify this simple doubt and apologize for the ignorance but until now I had not given much importance to the connection with the database, thanks!