What is the right way to connect to the Mysqli database

Asked

Viewed 24,249 times

10

I have a question that has brought me several incompatibilities. With the evolution of PHP and Mysql, more recent versions have emerged, this way Mysqli. That’s where my problem lies, I would like to know what is the right way to connect.

With Mysql it was:

$con = mysql_connect("localhost","root","");

And with the Mysqli ?

$mysqli = new mysqli("localhost","root","","nome-tabela");

or

$mysqli = mysqli_connect("localhost","root","");

When I look at the PHP manual, there’s a more object-oriented approach, but I’ve never seen it this way.

  • 2

    Both work well. It goes from your style of use. I particularly like the functional model, but it’s just a matter of taste and context, the functionality is identical. And the good thing is that mysqli is very similar to mysql, so the migration from one to another is very simple (even being specialized in Mysql, any alternative is inferior)

  • 2

    Have you considered using PDO? mysql_ are deprecated PHP functions.

4 answers

14


There is no right way, both the object-oriented style and the procedural serve for a particular case.

In new OO-style preference designs it is more practical because it is not necessary to pass the connection variable to other methods like query(), fetch_all() etc..

<?php
//Estilo orientado a objetos
$mysqli = new mysqli("localhost", "user","password","database");
$res = $mysqli->query("SELECT * FROM tabela");
$itens = $res->fetch_all(MYSQLI_ASSOC);

In the case of a system already written to migration of mysql functions_* should be exchanged for the procedural style of mysqli because it has less impact on the change what changes is the order of the parameters and the obligation to pass the connection in the functions.

<?php
//Estilo procedural
$mysqli = mysqli_connect('localhost', 'usuario', 'senha', 'database');
$res = mysqli_query($mysqli, 'SELECT * FROM tabela');
$itens = mysqli_fetch_all($res, MYSQLI_ASSOC);

3

$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link)); 

I use it that way.

0

If you want to test the connection and display a message with Ok button

$con = mysqli_connect("localhost", "root", "", "dbname");

if(!$con){
  die("Falha na conexao: " . mysqli_connect_error());
}else{
  echo "
  <script type="text/javascript">
  alert("Conexao realizada com sucesso.");
  </script>";
}

0

Using mysqli OO in a Singleton. Returns the connection that is only created if it is used. Avoid passing variable throughout the code. Avoids too much code.

function db(): mysqli
{
    static $db;
    $db OR $db = new mysqli('localhost', 'usuario', 'senha', 'database');
    return $db;
}

echo db()->query('SELECT 1+1 AS `soma`')->fetch_object()->soma;

Browser other questions tagged

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