0
I have the function below that makes the insertion of a new record in a database.
// INSERE UM NOVO REGISTRO NO BANCO DE DADOS
function save($table = null, $data = null) {
$_SESSION['message'] = null;
$_SESSION['type'] = null;
$database = open_database();
$columns = null;
$values = null;
foreach ($data as $key => $value) {
$columns .= trim($key, "'") . ", ";
$values .= "'$value', ";
}
$columns = rtrim($columns, ', ');
$values = rtrim($values, ', ');
$sql = "INSERT INTO " . $table . " ($columns) " . "VALUES " . "($values);";
//echo $sql; //usado apenas para depurar
try {
$database->query($sql);
if (!$database->errno == 1452) {
echo "<script type='text/javascript'>alert('Existe uma Informação duplicada no Banco de Dados');</script>";
}
$_SESSION['message'] = "Registro inserido com sucesso!";
$_SESSION['type'] = 'success';
} catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao!';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
I am unable to get the Mysql error code and present a message to the user. In this case here, problems with reference.
I used this link here from the forum as guidance, but it didn’t work: Handle Mysql error
Where am I going wrong?
but what would be the error returned with these settings, what error you are getting ?
– MichaelCosta
@Michaelcosta, when I file a form, the data is not recorded. Then I blur the line where I do an echo $sql and with that the system shows me the complete sql statement. If I copy this instruction and run in the database directly, Mysql reports missing integrity with 1452 error.
– Flávio Kowalske
put here the full statement that is sent in $sql..
– MichaelCosta
As far as I understand you want to show an msg to the user about the error... but you know that this error, is because you are trying to register something in the bank, which depends on a key that is probably not registered ? a key Foreign.. you really just want to treat the same error ?
– MichaelCosta
type to tell the user, that first he must register 'ABC' and then register 'XYZ'
– MichaelCosta
even @Michaelcosta you can see that I tried to catch the error in the code but it did not work.
– Flávio Kowalske