所以我有一个应该处理所有数据执行操作的函数:sql
function loadResult($sql)
{
$this->connect();
$sth = mysql_query($sql);
$rows = array();
while($r = mysql_fetch_object($sth)) {$rows[] = $r;}
$this->disconnect();
return $rows;
}
我想将其转换为 pdo,这就是我到目前为止所拥有的:pdo
function loadResult($sql)
{
$this->connect();
$sth = $this->con->prepare($sql);
//execute bind values here
$sth->execute();
$rows = array();
while ( $r = $sth->fetch(PDO::FETCH_OBJ) ) {$rows[] = $r;}
$this->disconnect();
return $rows;
}
下面是一个函数示例,介绍如何使用它来查看数据库中的数据:
function viewtodolist()
{
$db=$this->getDbo(); //connect to database
$sql="SELECT * FROM mcms_todolist_tasks";
//maybe the bind values are pushed into an array and sent to the function below together with the sql statement
$rows=$db->loadResult($sql);
foreach($rows as $row){echo $row->title; //echo some data here }
}
我刚刚拉出了重要的片段,所以一些变量和方法来自其他 php 类。不知何故,mysql 查询工作正常,但 PDO 查询让我头疼如何在 viewtodolist() 函数中包含绑定值参数表以使其可重用。欢迎任何建议/建议。
由于现有函数接受完全格式的 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...
你可以用参数化查询做一些更聪明的事情 - 例如,将变量绑定到输出参数,准备一次查询并使用不同的参数多次执行它 - 但这些将需要对调用代码的工作方式进行更多更改。