patternphpMinor
Programming MySQLi prepared statements
Viewed 0 times
mysqlistatementsprogrammingprepared
Problem
I'm programming code with MySQLi prepared statements. I'm a beginner and just want to ask to experts if my code is correct.
function getPaymentMethodName( $id ) {
global $mysqli;
if ( $stmt = $mysqli->prepare( 'SELECT name FROM `payment_methods` WHERE id = ?' ) ) {
if ( $stmt->bind_param( 'i', $id ) ) {
if ( $stmt->execute() ) {
$stmt->bind_result( $name);
if ( $stmt->fetch() ) {
$stmt->close();
return $name;
}
}
}
}
$stmt->close();
return false;
}Solution
Let mysqli do the error detection for you:
This makes mysqli throw exceptions when errors occur inside mysqli function calls, instead of failing silently and creating the need for you to manually detect these errors. You only need to call
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);This makes mysqli throw exceptions when errors occur inside mysqli function calls, instead of failing silently and creating the need for you to manually detect these errors. You only need to call
mysqli_report once before making mysqli function calls.Code Snippets
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);Context
StackExchange Code Review Q#75229, answer score: 4
Revisions (0)
No revisions yet.