无法在 php 便便中插入数据

can't insert data in php poo

我一直在学习关于 oop php 的教程,并且我正在做 crud 的 C,其中我有一个具有其属性的用户。当我在 bd 中插入时,它只是保存 () 或 {()},在这个人使用的例子中 ` public 函数保存(){

   $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;
}

`

但是当我使用它时,我只能在数据库上保存 {()}。我尝试从 getter 中删除 {},并将属性保存在新变量中并将其写入查询中,但我无法使其工作。 Here it's my db

和the error I get

感谢您的回答:)

要避免 sql 注入,您应该使用准备好的语句。它们带有 PDO,使用起来非常简单。看看下面的例子。

$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;

此外,您可以通过 PDO 将 sql 查询的执行包装在 try/catch 块中。因此,如果发生任何异常,您可以捕获它并查看到底出了什么问题。

try {
    // execute your logic here
} catch (PDOException $e) {
    var_dump($e, $this->db->errorInfo());
}

希望这对您有所帮助。

除此之外,您的 SQL 语法出现错误。 rol 后的最后一个逗号。此外,错误消息说,键 uq_email 的条目 () 已经存在。您可以使用上面显示的 try/catch 块捕获这种异常。