I have a form to add a new monitoring to a User. For that I use prepare statement with mysqli.
mysqli code :
function addMonitoring( mysqli $db, string $date, int $time, int $num_user, int $num_action, string $remark ): int
{
if(
$stmt = $db->prepare( 'INSERT INTO monitoring (
`date`,
`time`,
`num_user`,
`num_action`,
`remark`
)
VALUES ( ?, ?, ?, ?, ? )
')
) {
$stmt->bind_param( 'siiis', $date, $time, $num_user, $num_action, $remark );
$stmt->execute();
$stmt->close();
if(
$stmt = $db->prepare( 'SELECT m.id FROM monitoring m ORDER BY m.id DESC LIMIT 1')
)
{
$stmt->execute();
$stmt->store_result();
$stmt->bind_result( $id );
if( $stmt->fetch() ) {
return $id;
}
$stmt->close();
}
}
return 0;
}
And I try to display errors for tests, so I put a string type to my $time var and I want to know how to not show the error message seen here :
Having a message like 'An error occurred'
Code in the view to add the monitoring
if( isset( $_POST['add'] ) ) {
// dd($_POST);
addMonitoring( $db, $_POST['date'], $_POST['time'], $_POST['num_user'], $_POST['action'], $_POST['remark'] );
redirect( '/user/?num_user='.$_POST['num_user'] );
}
For exemple, if I don't use prepared statement, and I do that :
$query = "INSERT INTO monitoring (
`date`,
`time`,
`num_user`,
`num_action`,
`remark`
)
VALUES ( $date, $time, $num_user, $num_action, $remark )"
$result = mysqli_query( $db, $query );
$query = "SELECT m.id FROM monitoring m ORDER BY m.id DESC LIMIT 1";
$result = mysqli_query( $db, $query );
return ( !( $result === false ) && ( $row = mysqli_fetch_row( $result ) ) )?$row[0]:0;
I can return a int or 0 if mysql encounter a problem, so I can display a custom message if I have '0'