1

I have a prepared statement in PDO with multiple parameters, is there a way to bind the parameters in group, or chain the calls so as to avoid tediously calling bindParam for every item ?

What it looks like right now (I have even more parametrized queries elsewhere):

$stmt = $pdo->prepare("INSERT INTO users (name, pass, mail, created, timezone_name, hash_pass, salt) VALUES (:name, :pass, :mail, :created, :timezone, :hashed, :salt") ;

$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->bindParam(':mail', $mail, PDO::PARAM_STR);
$stmt->bindParam(':created', $date, PDO::PARAM_INT);
$stmt->bindParam(':timezone', $timezone, PDO::PARAM_STR);
$stmt->bindParam(':hashed', $hash, PDO::PARAM_STR);
$stmt->bindParam(':salt', $salt, PDO::PARAM_STR);

$stmt->execute();
blackbird
  • 1,129
  • 1
  • 23
  • 48

3 Answers3

4

Do it at execute time?

$stmt->execute(array(':name' => $name, etc....))

Using the formal bindParam() really only makes sense if you're going to be executing the statement in a loop and will be changing the values in $name and the other variables in the loop. If it's a fire/forget single-execution query, might as well just pass the values in the execute() call and skip the formal binding - it's a lot of extra work for basically no benefit.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Will this implicitly bind them though ? What I'm trying to do is have PDO properly escape them to protect against injections – blackbird Feb 10 '16 at 15:31
  • there's no binding at all, except for the duration of the `execute()` call. The end-result is the same as if you had bound those values. you still get the injection defense and whatnot, just no permanent link between a placeholder and a php var. – Marc B Feb 10 '16 at 17:14
1

Yes there is an alternative:

$stmt = $pdo->prepare("INSERT INTO users (name, pass, mail, created, timezone_name, hash_pass, salt) VALUES (?, ?, ?, ?, ?, ?, ?)") ;
$values = [$name, $pass, $mail, $date, $timezone, $hash, $salt];
$stmt->execute($values);

You have positional parameters the one I'm showing you and you have named parameters, Marc B's example.

Choose which one suits you.

Side note: you can never mix positional and named parameters.

Daan
  • 12,099
  • 6
  • 34
  • 51
0

You can do it like this:

$stmt = $pdo->prepare("INSERT INTO users (name, pass, mail, created, timezone_name, hash_pass, salt) VALUES (:name, :pass, :mail, :created, :timezone, :hashed, :salt");

$stmt->execute([
    ':name' => $name,
    ':pass' => $pass,
    ':mail' => $mail,
    ':created' => $created,
    ':timezone' => $timezone,
    ':hashed' => $hashed,
    ':salt' => $salt
]);
Tom
  • 606
  • 7
  • 28