What is the right way to connect to the MySQLi database

8

I have a question that has brought me various incompatibilities. With the evolution of PHP and Mysql, more recent versions have appeared, this way the Mysqli. This is where my problem resides, I would like to know which is the correct way to connect.

With Mysql it was:

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

What about Mysqli?

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

or

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

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

    
asked by anonymous 23.09.2014 / 20:29

2 answers

11

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

In new projects of preference to OO style 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 case of a system already written to migration of mysql_ * functions must be changed by the procedural style of mysqli because it has less impact on the change what changes the order of the parameters and the obligation to pass the connection on 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);
    
23.09.2014 / 20:42
3
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link)); 

I use it that way.

    
23.09.2014 / 20:31