Php 将mysql转换为pdo

Php 将mysql转换为pdo,php,pdo,Php,Pdo,所以我有一个函数应该处理所有的数据执行操作:sql function loadResult($sql) { $this->connect(); $sth = mysql_query($sql); $rows = array(); while($r = mysql_fetch_object($sth)) {$rows[] = $r;} $this->disconnect();

所以我有一个函数应该处理所有的数据执行操作: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()函数中包含bindValue参数以使其可重用。欢迎任何建议。

由于您现有的函数接受完全格式的SQL字符串,没有占位符,因此您不需要使用
prepare
+
bind
。您编写的代码应该可以正常工作,或者您可以使用它一步执行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...

对于参数化查询,您可以做一些更聪明的事情,例如将变量绑定到输出参数,准备一个查询并使用不同的参数执行多次,但这些都需要对调用代码的工作方式进行更多的更改。

在您的情况下,由于查询没有参数,您没有任何东西可绑定。使用上面的代码,如果我使用insert语句,是否有一种方法可以执行批量操作,例如在正常时间以最佳性能插入多个值?@user1850720 no,我认为您在这里描述的内容需要您存储或返回准备好的语句(
$sth
),以便您可以使用不同的参数对其多次调用
execute
。@user1850720…或者我认为您可以将数组数组传递给函数,并对每个内部数组循环调用
execute