Close an execution or not when there is a Pdoexception error?

Asked

Viewed 30 times

-2

When implementing Pdoexception is there a need to use die or Exit to complete execution in case of errors? or just return an "echo" stating the error and let the execution of the script follow?

My current implementation:

define("HOST", 'localhost');
define("USER", 'root');
define("PASS", '');
define("NAME", 'script');

//Conectamos ao banco de dados
try {
    $db = new PDO("mysql:host=".HOST.";dbname=".NAME.";charset=utf8", "".USER."", "".PASS."");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e) {
    die("Erro ao conectar no banco de dados");
}

// Função basica para gerenciamento PDO
function sql($db, $q, $params, $return) {
    
    try {

        //prepara a querry
        $stmt = $db->prepare($q);

        //executa a query
        $stmt->execute($params);
        
        // retorna no formato solicitado pela variavel
        if ($return == "rows") {
            return $stmt->fetch();
        }elseif ($return == "rowsall") {
            return $stmt->fetchAll();
        }elseif ($return == "count") {
            return $stmt->rowCount();
        }elseif( $return == "lastid"){
            return $db->lastInsertId();
        }
        
    }catch(PDOException $e) {
        
        echo "DataBase Erro: ".$e->getMessage();
        die();
        
    }catch(Exception $e) {
        
        echo "Erro Geral: ".$e->getMessage();
        die();
        
    }
    
}
  • If the database fails, it makes sense to run the rest of the script?

  • @Woss and as for Try/catch, and need to use in all query? as it is in the function above?

1 answer

-1

As it says in the Woss comment: ask yourself if it makes sense for the script to run if there is an error in the database. Probably not, so it’s interesting to finish the execution.

Browser other questions tagged

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