May pass $pdo
as an argument for functions or to create a class to share the connection between methods. Do not inject global or external variables into a function because they can break the behavior of the function which is a reusable piece of 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, did not repeat the validation with $_GET
but she still needed, use the function header()
to redirect the user 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 ...';
}
}
May pass
$pdo
as a function argument ...$_GET
should also be global or external variables should not be injected directly like this. Another option is to create a class for sharing$pdo
among the methods.– rray
... pass as argument to the function ... can you show me that?
– Marcos Vinicius