I am creating a library in PHP
to connect to the database and manipulate data from it, but I do not know what the best option is to handle the errors, whether it is best to use try/catch
, echo/return
or die
.
I'm currently using multiple if/else
to go through (validate) the data, in case of error I display a echo
with error and give return false
(not to execute the remaining code) I just continue my checks and at the end return true
or array
(depending on the function). Here is an example of my simplest function (the deletar
):
function deletar($tabela, $where = NULL)
{
if(!function_exists("conectar"))
{ //falta include de conexao.php
echo "Não há uma conexão ativa com o seu banco de dados!\n<br><i>Inclua a página ../conexao.php<br>";
return false;
}
else
{
//conexao feita
if($tabela)
$tabela = "DELETE FROM ".$tabela." ";
else
{
echo "<br>Não foi indicada nenhum tabela.<br>";
return false;
}
$where = minwhere($where);
echo $sql = $tabela.$where;
if($conn = conectar())
{
if($result = $conn->query($sql))
{
$stmt = $conn->prepare( $sql );
if($result = $stmt->execute())
echo "<br>Deletado!<br>";
else
echo "<br>Query inválida!<br>";
$conn = null;
return true;
}
else
{
echo "<br>Query inválida!<br>";
return false;
}
}
else
{
echo "<br>Não foi possível conectar-se ao banco de dados!<br>\n<i>Verifique as variáveis do arquivo ../conexao.php</i>";
return false;
}
}
};
Follow the remainder of the library (for if someone wants to review other functions).
What can be better at handling errors? Is the way I'm doing a valid alternative or bad code?