【问题标题】:convert mysql to pdo将mysql转换为pdo
【发布时间】:2013-09-14 15:50:07
【问题描述】:

所以我有一个应该处理所有数据执行操作的函数: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  }  
}    

我刚刚提取了重要的sn-ps,所以一些变量和方法来自其他php类。不知何故,mysql 查询工作正常,但 PDO 查询让我很头疼如何在 viewtodolist() 函数中包含 bindValue 参数以使其可重用。欢迎任何建议/建议。

【问题讨论】:

  • 在您的情况下,您没有任何要绑定的内容,因为您的查询没有参数。

标签: php pdo


【解决方案1】:

由于您现有的函数接受完整格式的 SQL 字符串,没有占位符,因此您不需要使用 prepare + bind。您编写的代码应该可以正常工作,或者您可以使用PDO::query() 一步执行 SQL。

如果您想使用参数化查询,那么您的loadResult 函数将不得不进行一些更改,就像您编写 SQL 的方式一样。您提供的示例 SQL 实际上没有任何可以转换为参数的内容 (column names and table names can't be parameters as discussed here),但我将使用一个虚构的变体:

// 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...

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

【讨论】:

  • 使用上面的代码,如果我使用的是插入语句,有没有办法可以执行批量操作,比如在理智的时候以最佳性能插入多个值?
  • @user1850720 不,我认为您所描述的内容需要您存储或返回准备好的语句 ($sth),以便您可以使用不同的参数多次调用 execute .
  • @user1850720 ...或者我想你可以将一个数组数组传递给函数,然后循环调用每个内部数组的execute
猜你喜欢
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
  • 2023-03-03
  • 2010-09-20
相关资源
最近更新 更多