Which database connection is best?

Asked

Viewed 347 times

1

I started working and am updating the company system, it currently uses this connection:

$link = mysqli_connect("0.0.0.0", "teste", "teste", "teste");
mysqli_set_charset($link, "utf8");

if (mysqli_connect_errno()) {
    printf("<br> Nao foi possivel conectar. Erro: %s\n", mysqli_connect_error());
    exit();
}

$database_host = "0.0.0.0";
$database_user = "teste";
$database_password = "teste";
$database_db = "teste";

$conexao = new mysqli($database_host, $database_user, $database_password, $database_db);
mysqli_set_charset($conexao, "utf8");
if ($conexao->connect_error) {
    die("A conexão falhou!");
}
date_default_timezone_set("America/Sao_Paulo");

I learned and use this kind:

class ConexaoBanco extends PDO {

    private static $instancia = null;

    public function ConexaoBanco($dsn, $usuario, $senha) {
        //Construtor da classe pai PDO
        parent::__construct($dsn, $usuario, $senha);
    }

    public static function getInstancia() {
        if (!isset(self::$instancia)) {
            try {
                // Cria e retorna uma nova conexão
                self::$instancia = new ConexaoBanco("mysql:dbname=teste;host=0.0.0.0", "teste", "teste");
            } catch (Exception $e) {
                echo 'Erro ao conectar o banco de dados!';
                exit();
            }
        }
        return self::$instancia;
    }
}

Which one is better? Because?

  • PDO and Mysqli are two different Apis, PDO can communicate with mysql and other banks, while mysqli is unique to mysql, note that both have differences of use, this question is well detailed: https://answall.com/q/8302/3635

1 answer

1


There is no better or worse, in this case, because you use the mysql database. If you used another database, such as Postgresql, you would need to use the PDO. Because the PDO supports more banks, while the mysqli supports mysql database only.

There is a debate of which is better or worse. (here for example)

But in my view both have a lot of safety and performance. If you are used to using PDO, go ahead and continue.

Browser other questions tagged

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