由于您现有的函数接受完整格式的 SQL 字符串,没有占位符,因此您不需要使用prepare
+ bind
。您编写的代码应该可以正常工作,或者您可以使用PDO::query()一步执行SQL。
如果您想使用参数化查询,那么您的loadResult
函数必须稍作改变,编写 SQL 的方式也是如此。您给出的示例 SQL 实际上没有任何可以转换为参数的内容(列名和表名不能是此处讨论的参数),但我将使用一个假想的变化:
// Get the todo tasks for a particular user; the actual user ID is a parameter of the SQL
$sql = "SELECT * FROM mcms_todolist_tasks WHERE user_id = :current_user_id";
// Execute that SQL, with the :current_user_id parameter pulled from user input
$rows = $db->loadResult($sql, array(':current_user_id' => $_GET['user']));
这是将用户输入放入查询中的一种很好的安全方法,因为 MySQL 知道哪些部分是参数,哪些部分是 SQL 本身的一部分,并且 SQL 部分没有任何人可以干扰的变量。
使这项工作与您现有的工作一起使用的最简单方法loadResult
函数会是这样的:
// Function now takes an optional second argument
// if not passed, it will default to an empty array, so existing code won't cause errors
function loadResult($sql, $params=array())
{
$this->connect();
$sth = $this->con->prepare($sql);
// pass the parameters straight to the execute call
$sth->execute($params);
// rest of function remains the same...
您可以使用参数化查询做一些更聪明的事情 - 例如将变量绑定到输出参数,准备一次查询并使用不同的参数多次执行它 - 但这些将需要对调用代码的工作方式进行更多更改。