Doubt with connection to php database with mysql

3

I am learning about php and mysql, I see several tutorials on the internet and a doubt that I came up with is, I see that if you create several variables and then you put these variables in the command,

$servidor = "localhost";
$usuario = "root";
$pass = "";
$dbname = "vendas";
$conn = mysqli_connect($servidor, $usuario, $pass, $dbname);

Why not put it in charge ?? example:

$conn = mysqli_connect('localhost','root','','vendas');

What is the purpose of using the variables in this case?

    
asked by anonymous 10.07.2016 / 19:34

2 answers

4

Basically, both are personal choices. In practice, neither way is "better" or "worse" than the other, and they work the same way.

If you have a connection just at the beginning of the code, it does not get in the way of putting it directly into the function. If you are going to use this data after other logical parts of the code, leaving the data in variables at the beginning of the code makes maintenance easier.

Now, as in the first example, where the connection function is next to the variables, it does not make much sense. In short: give it anyway, use whatever is most convenient or desirable for your specific case.

It is not part of the question, but I think it is good to comment that it is more important to separate the variables, for reuse purposes, to have the connection in a separate file, for example dbconnect.php that makes the connection for you, and all pages that use the DB you use require_once( 'dbconnect.php' ); , so it will only have one place to adjust in case of a server change or configuration in general.


Note: In principle the question appears to be one that generates "opinion-based" answers, which is usually a reason for closing, but how is it clarified to see if there is any reason, not "which is better", I found it appropriate to answer

    
10.07.2016 / 21:16
0

It is best for organization, and the like, for when someone other than yourself can understand more easily. And when you transfer to an online server, you do not have to keep looking for where you connected to the bank, you just trade the value of the variables. They are good practices of code organization and reuse. I hope I have helped

    
10.07.2016 / 19:37