As an addition to the response of @rray
, I would like to highlight here the advantage of using execute
with array
compared to PDOStatment::bindValue
method.
Often the data we want to pass bindValue
may be in array
. Utilization could be laborious if you were to set one by one.
Example:
$array = array('nome'=>'Alisson', 'idade'=>20);
$query = $conn->prepare("INSERT INTO table (nome,idade) VALUES (:nome, :idade)");
$query->bindValue(':nome', $array['nome'], PDO::PARAM_STR);
$query->bindValue(':idade', $array['idade'], PDO::PARAM_STR);
When I needed to do an operation to pass the values from a array
dynamically to bindValue
, the first thing I thought to slow down my work was to do a foreach
.
$array = array('nome'=>'Alisson', 'idade'=>20);
$query = $conn->prepare("INSERT INTO table (nome,idade) VALUES (:nome, :idade)");
foreach ($array as $key => $value) {
$query->bindValue(":$key", $value, PDO::PARAM_STR);
}
At the end of the day it was more advantageous to use execute
passing array
.
Small difference
As hard as it may seem, I did notice a small difference between the two. This is only noticeable when we use the ?
character to perform 'parameter binding'.
See:
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindValue(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
Note that it is necessary to define the position of the queries ( ?
) to be able to define which value will be bound to that parameter.
But in the case of execute
it's a bit different. The parameter binding will occur according to the position of the element in array
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));
The count in this case occurs from 0
. If you attempt to erroneously name a array
(numerically), an error will occur while attempting to run the execute
method:
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(1 => $calories, 2 => $colour));
PHP warning: PDOStatement :: execute (): SQLSTATE [HY093]: Invalid parameter number: parameter was not defined