PHP 8.1: MySQLi: Bind in Execute
Since PHP 8.1, the MySQLi extension's mysqli_stmt_execute
function and mysqli_stmt::execute
method (which are aliases) accept a $params
parameter. If passed, the passed values will be bound to the statement as strings.
Prior to this change, parameterized SQL queries had to be bound with variables explicitly with a bind_param
call:
$statement = $db->prepare('SELECT * FROM posts WHERE pid = ?');
$statement->bind_param('s', $postId);
$statement->execute();
Since PHP 8.1, it is possible to directly pass the parameters to the execute
method. This simplifies the parameter binding calls which were otherwise had to be done with a bind_param
call. This change brings feature parity with PDOStatement::execute
method, which already accepts parameters.
The snippet above can be simplified in PHP 8.1 as following:
$statement = $db->prepare('SELECT * FROM posts WHERE pid = ?');
$statement->execute([$postId]);
Similar to the object-oriented example above, procedural MySQLi API also accepts the parameters in mysqli_stmt_execute()
function:
$statement = mysqli_prepare($connection, 'SELECT * FROM posts WHERE pid = ?');
- mysqli_stmt_bind_param($statement, 's', $postId);
- mysqli_stmt_execute();
+ mysqli_stmt_execute($statement, $postId);
Updated mysqli_stmt_execute
synopsis
- function mysqli_stmt_execute(mysqli_stmt $statement): bool {
+ function mysqli_stmt_execute(mysqli_stmt $statement, ?array $params = null): bool {
}
Updated mysqli_stmt::execute
synopsis
class mysqli_stmt {
// ...
- public function mysqli_stmt_execute(): bool {
+ public function mysqli_stmt_execute(?array $params = null): bool {
}
}
Backwards Compatibility Impact
Classes that extend the mysqli_stmt
class now must also support the $params
parameter.
Passing the parameters to the mysqli_stmt_execute()
function / mysqli_stmt::execute()
methods does not cause any warnings, but note that parameter will not be bound, and may cause errors.