Insert php with object as parameter

Asked

Viewed 432 times

5

I’d like to understand how I can do an insert function in php that uses an object as a parameter. Example:

class Aluno{
   private $nome;
   private $curso;
}

getters e setters...

public function insere(Aluno $aluno){
// suponho que aqui fica a definição dos atributos e o retorno do mysqli_query (não tenho certeza)

}

My question is how I can get this function to insert a record into the database, when it is simply called by an instantiated object. And I would like this function not to be changed in the parameter, even if more attributes are placed in the class. I need it to always be a Student object. I would also like to understand how I can use the return of this function.

  • First it is important that you relate your student entity from the bank(table) to your Student class. Then just do Insert into normally, using getters to assign table column values.

  • What really is the problem ? It is hard to understand, what is really the problem based on this example, and your explanation is also unclear ?

  • Edilson, I said above that I need to understand how to do a function using an object as a parameter, I don’t understand exactly how to implement the function, I even put a comment assuming what I believe it should be, but I’m not sure how to do it.

1 answer

1

Hey, good night, man. I’m a beginner in php, and I don’t use mysqli either (I’m using PDO),

$pdo = new PDO("mysql:host=localhost;dbname=nome_banco", "usuario_banco", "senha_banco");
$insert = $pdo->prepare("INSERT INTO NomeTabela (nome,curso) VALUES (:nome,:curso);");
$insert->bindValue(":nome",$aluno->nome);
$insert->bindValue(":curso",$aluno->curso);
$insert->execute();
  • 2

    Concaterizing values in SQL creates a security vulnerability (SQL Injection). Imagine if someone names: "; DROP DATABASE; --

  • 2

    Hello, Thanks for the comment, I had responded when I started the studies in php/database. I made the modifications.

Browser other questions tagged

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