DEV Community

Slava Rozhnev
Slava Rozhnev

Posted on

PHP 8.1: MySQLi: Bind in Execute

PHP have two libraries are mainly used to interact with the MySQL database:
PDO (PHP Data Objects) - a universal driver that allows you to work with various databases, including MySQL
MySQLi (MySQL improved) is an extension of the relational database driver used in the PHP programming language to provide access to MySQL databases.

Although MySQLi shows slightly better performance with prepared statements, in most cases I chose PDO because of its convenient binding syntax.

Just compare:

$mysqli_statement = $mysqli->prepare('SELECT * FROM posts WHERE id = ? and author = ?');
$mysqli_statement->bind_param('ds', $postId, $author);
$mysqli_statement->execute();
Enter fullscreen mode Exit fullscreen mode

Test above code on PHPize.online

With concise PDO:

$pdo_statement = $pdo->prepare('SELECT * FROM posts WHERE id = ? and author = ?');
$pdo_statement->execute([$postId, $author]);
Enter fullscreen mode Exit fullscreen mode

Run code here

However, since PHP 8.1, thanks to an improvement suggested by Kamil Tekiela
everything has become much simpler and the syntax of MySQLi has become as pleasant as in PDO:

$mysqli_statement = $mysqli->prepare('SELECT * FROM posts WHERE id = ? and author = ?');
$mysqli_statement->execute([$postId, $author]);
Enter fullscreen mode Exit fullscreen mode

https://phpize.online/s/DU

Top comments (0)