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();
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.
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.
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
]);