Doubt with Mysqli and PHP OO

1

I have the following code snippet:

public function registerUser($link, $nome, $sobrenome, $apelido) {
    $sql = "INSERT INTO estudo_oo (id, nome, sobrenome, apelido) VALUES ('', '$nome', '$sobrenome', '$apelido') ";
    if(!mysqli_query($link, $sql)) {
        die('Error: ' . mysqli_error($link));
    }
}

And my question is: Would I ALWAYS have to pass variables by parameter there in function? Why type, if I have a form with multiple fields for example, would I really have to pass all variables there?

I did some tests and tried to save the form without passing the variables by parameter, but I was not successful, hence I came to the question.

    
asked by anonymous 05.08.2014 / 00:51

3 answers

2

Responding more directly to your question:

  

I would have to ALWAYS pass the variables by parameter there in function ?

At some point you have to pass the arguments, either by defining class properties, or as method arguments. Which of the two ways (or both) you will use depends only on your decisions for the project.

    
05.08.2014 / 15:19
1

In object orientation we have class properties, which are nothing but variables within the scope of the class.

mysqli allows both the procedural method (which is what you are using) as an object-oriented method.

I will not go into more detail, but here is a simple example of how to use the properties:

<?php

class Usuario {

    // A propriedade com uma conexão
    protected $dbConnection;

    // Método construtor para passagem do parâmetro (nesse caso sua conexão com banco)
    public function __construct(mysqli $dbConnection)
    {
        // Injeta a conexão criada na classe
        $this-> dbConnection = $dbConnection;
    }

    public function registerUser($nome, $sobrenome, $apelido) 
    {
        // Recomendo o uso de prepared statments para inserir os parâmetros
        $sql = "INSERT INTO estudo_oo (id, nome, sobrenome, apelido) VALUES ('', '$nome', '$sobrenome', '$apelido') ";

        // Procure usar Exceptions para tratamento de erros
        try {
            $this->query($sql);
        } catch (mysqli_sql_exception $e) {
            return $e->message;
        }

        return true;

    }
}

// Como usar:

$link = new mysqli('localhost', 'user', 'pass');

$usuario = new Usuario($link);
$usuario->registerUser('João', 'Lucas', 'Jão');

These were just a few tips on how to implement. Other suggestions are use PDO or MySql instead < a> and read a little more of basic in modern PHP development .

    
05.08.2014 / 01:11
1

You can set default values for the parameters you do not want to always pass:

public function registerUser($link, $nome, $sobrenome=null, $apelido=null) {

}

Note: Since you're using mysqli, I strongly recommend using prepared statements instead to concatenate the variables directly in the query.

    
05.08.2014 / 03:11