Yeah, but you can get better,
Every time you call this->conectar()
to get a new connection, you create a new instance of the connection object with the database, then at a certain point in the application, you need to run 3 querys and 3 connections will be created with the same database
By instantiating the class mysqli
, you can pass the database name in the fourth parameter, so you don’t need to add the database to each query (INSERT INTO my_db.my_table ...
)
In this class you have two functions, one that connects and another that performs the registration of a product, but what about the registration of users? You would have to mix the functions of products and users or create a new class and repeat the connection function
Code with some more improvement ideas:
class Banco {
private const host = "host";
private const banco = "nome_do_banco";
private const user = "meu_usuario";
private const password = "minha_senha";
private static $conexao = null;
public static function conectar(){
if (self::$conexao != null) {
return self::$conexao;
}
self::$conexao = new mysqli(self::host,self::user,self::password, self::banco);
if(self::$conexao->connect_error){
die('Falha na conexão:'.self::$conexao->connect_error);
}
return self::$conexao;
}
}
class Produto extends Banco {
public function cadastrar($produto, $preco){
$conectar = self::conectar();
$sql = 'insert into produto(produto,preco) value("'.$produto.'","'.$preco.'");';
if($conectar->query($sql) === TRUE){
return 'cadastrado';
}else{
return 'Erro: '.$conectar->error;
}
}
}
class Usuario extends Banco {
public function cadastrar($nome, $idade){
$conectar = self::conectar();
$sql = 'insert into usuario(nome,idade) value("'.$nome.'","'.$idade.'");';
if($conectar->query($sql) === TRUE){
return 'cadastrado';
}else{
return 'Erro: '.$conectar->error;
}
}
}
I imagine you are starting programming in PHP, so I recommend you take a look at PSR-2 which is a coding style guide and that Sopt question about SQL Injection
In the case of the product class it is
$conectar = self::conectar();
? Would not be$conectar = this->conectar();
?– Erick
Both work, no need to use the
this
because the method is static, but if you want it will work the same– Costamilam