Validate class that executes a sql query

1

Hello, I have the following code in my dao.php.

public function insert(){
    $this->conn->beginTransaction();
    try {
        $sql = "QUERY DO INSERT AQUI .......";
        $stmt = $this->conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $stmt->execute();
        $this->conn->commit();
    } catch (Exception $e) {
        $this->conn->rollback();
    }
}

In my controller:

public function insert(){
    $dao = new DAO($this->conn);
    return $dao->insert();
}

Here I call the insert class in my view to execute the insert.

$class = new Controller($conn);
//Insert
$class->insert();

Now the question, how do I do to validate this call? If it is executed it will show a message if no other is shown. Do I do this in my view or dao? It is like ? Thank you.

    
asked by anonymous 19.12.2017 / 14:57

1 answer

1

In your DAO you can add a method return being true or false :

public function insert(){
    $this->conn->beginTransaction();
    try {
        $sql = "QUERY DO INSERT AQUI .......";
        $stmt = $this->conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $response = $stmt->execute();
        $this->conn->commit();
        return $response;
    } catch (Exception $e) {
        $this->conn->rollback();
        return false;
    }
}

And in your View you can treat this return if it is true or false , for example:

$class = new Controller($conn);
//Insert
if($class->insert()){
    echo 'sucesso';
}else{
    echo 'erro';
}
    
19.12.2017 / 15:27