Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQLi execute without bind_param

The PHP documentation for 'execute' includes the example #2 (https://www.php.net/manual/en/mysqli-stmt.execute.php#example-1489) that looks like this :

$stmt = $mysqli->prepare('INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)');

$stmt->execute( ['Stuttgart', 'DEU', 'Baden-Wuerttemberg'] );

Notice there is no stmt->bind_param, the values are added as an array parameter of execute.

I tried to make this example to work by creating the table and running the code :

CREATE TABLE myCity
(
  Name         VARCHAR(99),
  CountryCode  VARCHAR(99),
  District     VARCHAR(99)
) ENGINE=INNODB DEFAULT CHARSET=UTF8MB4 COLLATE=UTF8MB4_UNICODE_CI

But it didn't work, nothing was inserted and there was no error message or warning. I also tried using variables instead of static values as parameters of execute but didn't work either.

Am I missing something? Did I misinterpret the example? So is bind_param necessary and execute should not get the values to insert?

I am using PHP version 7.2.18.

like image 451
Jose Manuel Abarca Rodríguez Avatar asked Mar 15 '26 03:03

Jose Manuel Abarca Rodríguez


1 Answers

Binding in execute is only available as of PHP 8.1. If you are running PHP 8.0, passing an extra parameter will throw an error.

If you use PHP 7 or earlier, passing the array as an argument to execute() triggers undefined behaviour. That's why you see no errors and it just doesn't work.

It's worth pointing out that this feature was available since PHP 5 in the PDO extension. PDO has more features and is easier to use, so if you don't have a strong need to use mysqli, use PDO instead.

like image 75
Dharman Avatar answered Mar 17 '26 16:03

Dharman