i'veen following a tutorial about oop php and I was doing the C of the crud, where I have a user with its attributes. When i'm doing the insert into the bd it just save () or {()}, in the example the person uses ` public function save(){
$sql = "INSERT INTO usuarios (nombre, apellidos, email, password,rol,) VALUES('{$this->getNombre()}',
'{$this->getApellidos()}','{ $this->getEmail()}','{$this->getPassword()}','user')";
$save = $this->db->query($sql);
$result=false;
if($save){
$result=true;
}
return $result;
}
`
But when I use it, I get only save {()} on the db. I tried erasing the {} from the getters, and saving the attributes in new variables and writting it in the query but I can't make it works. Here it's my db
And the error I get
Thank you for your answers :)
To avoid sql injection you should use prepared statements. These come with PDO and are pretty simple to use. Have a look at the following example.
$sql = "
INSERT INTO
usuarios
(nombre, apellidos, email, password,role)
VALUES
(:nombre, :apellidos, :email, 'user')
";
$stmt = $this->db->prepare($sql);
$result = $stmt->execute([
'nombre' => $this->getNombre(),
'apellidos' => $this->getApellidos(),
'email' => $this->getEmail()
]);
return $result;
Further more you can wrap the execution of your sql query via PDO in a try/catch block. So if any exception occurs, you can catch it and see, what exactly went wrong.
try {
// execute your logic here
} catch (PDOException $e) {
var_dump($e, $this->db->errorInfo());
}
Hope this helps.
Beside that your SQL Syntax got an error. The last comma after rol
. Further the error message says, that an entry ()
for the key uq_email
already exists. This kind of exeptions you can catch with the above shown try/catch block.