1
I’m wondering if this is really the right way to make a connection between php and mysql with the PDO class. The question is as follows: Each time I have a file that uses this connection it will create a new connection
Class PDOUtil {
public static final function conectar() {
try {
$conexao = new PDO('mysql:host=localhost;dbname=site_local', 'root', '');
} catch (PDOException $ex) {
echo $ex->getMessage();
if ($ex->getCode() == "2002") {
echo 'Oi infelizmente seu Host nao foi encontrado, verifique isso com o web-master.';
}
if ($ex->getCode() == "1049") {
echo 'Oi infelizmente seu banco nao foi encontrado, verifique isso com o web-master.';
}
if ($ex->getCode() == "1044") {
echo 'Oi infelizmente seu usuario nao foi encontrado, verifique isso com o web-master.';
}
if ($ex->getCode() == "1045") {
echo 'Oi infelizmente sua senha nao foi encontrada, verifique isso com o web-master.';
}
}
return $conexao;
}
}
an example of use
include '../config/PDOUtil.php';
$con = new PDOUtil();
$con->conectar();
Your connect class is static, so there’s no need to instantiate an object. This is a pattern called Singleton you could simply call it using $con = Pdoutil::connect(); from there just use the PDO object. $con->prepare("SELECT * FROM table"); $con->execute(); $return = $con->fetchAll(); And so on.
– Hiago Souza