在 pdo 中绑定多个值

2021-12-26 00:00:00 bind php pdo

是否有一种无需重复就可以在 PDO 中绑定多个值的简单方法?看看下面的代码:

Is there's an easy way of binding multiple values in PDO without repitition ? Take a look at the following code :

$result_set = $pdo->prepare("INSERT INTO `users` (`username`, `password`, `first_name`, `last_name`) VALUES (:username, :password, :first_name, :last_name)");

$result_set->bindValue(':username', '~user');
$result_set->bindValue(':password', '~pass');
$result_set->bindValue(':first_name', '~John');
$result_set->bindValue(':last_name', '~Doe');

$result_set->execute();

在这里,我以 4 次重复的方式绑定值.那么是否有一种简单的方法可以在 PDO 中绑定多个值?

Here, I binded values in a repepeated way which is 4 times. So is there's an easy way of binding multiple values in PDO ?

推荐答案

你总是可以在 execute() 的参数中绑定值,只要你觉得值被视为 <代码>PDO::PARAM_STR(字符串).

You can always bind values within the arguments of execute() as long as you're fine with the values being treated as PDO::PARAM_STR (string).

$result_set = $pdo->prepare("INSERT INTO `users` (`username`, `password`, `first_name`, `last_name`) VALUES (:username, :password, :first_name, :last_name)");
$result_set->execute(array(
    ':username' => '~user',
    ':password' => '~pass',
    ':first_name' => '~John',
    ':last_name' => '~Doe'
));

您可以像使用任何数组一样使用传递的数组:

You can use the array passed just like any array:

$user = "Nile";
$pdo->execute(array(":user" => $user));

相关文章