You can pass $pdo
as an argument to functions or create a class to share the connection between methods. Do not inject global or external variables within a function because they can break the behavior of the function which is a piece of reusable code.
function novo ($pdo, $registro){
}
function listar ($pdo){
}
function atualizar ($pdo, $registro){
}
function excluir($pdo, $id){
$stmt = $pdo->prepare("DELETE FROM tb_blog WHERE ID = ?");
if(!$stmt->execute(array($id))){
print_r($stmt->errorInfo());
}
echo "
<META HTTP-EQUIV=REFRESH CONTENT = '0;URL='>
<script type=\"text/javascript\">
window.location = \"index\";
</script>
";
return;
}
}
if (!empty($_GET['tipo']) && $_GET['tipo'] == 'blog' && !empty($_GET['funcao']) && $_GET['funcao'] == 'excluir'){
$id = !empty($_GET['id']) && ctype_digit($_GET['id'] ? $_GET['id'] : 0;
excluir($pdo, $id);
}
Class approach, I did not repeat the validation with $_GET
but it still needed, use the header()
function to redirect the user it does not make sense to use javascript for this
class blogDAO{
private $connection;
function __construct(PDO $pdo){
$this->connection = $pdo;
}
function novo($registro){
}
function listar(){
}
function atualizar ($pdo, $registro){
}
function excluir($id){
$stmt = $this->connection->prepare("DELETE FROM tb_blog WHERE ID = ?");
if(!$stmt->execute(array($id))){
print_r($stmt->errorInfo());
return false;
}else{
return true;
}
}
}
$daoBlog = new blogDAO(Database::connect());
if($_GET ...){
if($daoBlog->excluir($id)){
header('Location: index.php');
}else{
echo 'erro ...';
}
}