2
I’m creating a library in PHP
to make the connection to the database and manipulate data from it, but do not know what is the best option to handle the errors, if it is better to use try/catch
, echo/return
or die
.
I am currently using several if/else
to go through (validate) the data, in case of error I display a echo
with the mistake and I give a return false
(not to execute the remaining code), if there is no error, just continue my checks and at the end return true
or array
(depending on function). See 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;
}
}
};
Follows the rest of the library (if someone wants to analyze other functions).
What can improve error handling? The mode I’m doing is a valid alternative or bad code?
Enjoy and see this and here has an example of a Soen user-made Builder query that answers a lot about php.
– rray