I have doubts whether this would be the right way to make a connection using the PDO class

Asked

Viewed 201 times

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.

2 answers

3

Your script is right, however you will be creating a new connection each time you request it. Try this way using the default Singleton;

Class PDOUtil {
private static $oInstance;

public static function getConexao() {

  if (!(self::$oInstance instanceof PDO)) {
    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.';
      }
      exit;
    }

  }
  return self::$oInstance;
}

/* TORNA O CONSTRUTOR PRIVADO PARA PROIBIR DE INSTANCIA ESTA CLASSE */
private function __construct() {}

}

To use now you can always do this way:

$conexao = PDOUtil::getConexao();

This way only one connection will exist in your application and you can get it easily;

1

In PDO you only need a connection for the entire "existence" of the script, exactly the same would do with mysql_*.

$conn = new PDO(
    'mysql:host=localhost;dbname=example-pdo', 'andre', '123456',
    array(
        PDO::ATTR_PERSISTENT => true
    )
);

In the above example, we set our connection to persistent. A persistent connection is not closed at the end of the script, but stored in cache and reused when another script requests a connection using the same credentials.

Your form is correct!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.