PDO bindParam 成一个语句?

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

有什么办法可以将这些 bindParam 语句放入一个语句中吗?

Is there a way I can put these bindParam statements into one statement?

$q = $dbc -> prepare("INSERT INTO accounts (username, email, password) VALUES (:username, :email, :password)");
$q -> bindParam(':username', $_POST['username']);
$q -> bindParam(':email', $_POST['email']);
$q -> bindParam(':password', $_POST['password']);
$q -> execute();

我在可能的情况下使用之前准备好的 mysqli,我切换到 PDO 以获得 assoc_array 支持.在 PDO 的 php.net 网站上,它在单独的行上显示它们,在我看到的所有示例中,它都在单独的行上.

I was using mysqli prepared before where it was possible, I switched to PDO for assoc_array support. On the php.net website for PDO it shows them on seperate lines, and in all examples I have seen it is on seperate lines.

有可能吗?

推荐答案

上的示例 2execute 页面就是你想要的:

Example 2 on the execute page is what you want:

$sth->execute(array(':calories' => $calories, ':colour' => $colour));

您可能还想查看其他示例.使用问号参数,它将是:

You may want to look at the other examples too. With question mark parameters, it would be:

$q = $dbc -> prepare("INSERT INTO accounts (username, email, password) VALUES (?, ?, ?)");
$q->execute(array($_POST['username'], $_POST['email'], $_POST['password']));

如果只有这些列,您可以只写:

If those are the only columns, you can just write:

$q = $dbc -> prepare("INSERT INTO accounts VALUES (?, ?, ?)");
$q->execute(array($_POST['username'], $_POST['email'], $_POST['password']));

相关文章