本文介绍了在程序环境中使用PDO的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚从MySQL切换到PDO,并且正在使用准备好的语句.

I just switched from MySQL to PDO and i am using prepared statements.

我曾经有过MySQL的功能,在每个页面上我都做了类似的事情

I used to have function for MySQL and on every page i did something like

$Query = "UPDATE users SET f_name={$POST["first_name"]}, l_name={$_POST["last_name"]} ";
$SQL_obj->runquery($query, "update");

现在有了PDO和prepared语句,是否还需要创建函数还是只对每个查询都进行prepare(),bindValue()和execute()?

Now with PDO and prepared statements does it make sense to create function as well or just do prepare(), bindValue() and execute() on every query?

我似乎无法编写良好的PDO功能.有人可以建议吗?我的代码主要是程序性的.

I just cannot seem to write good PDO function. Can someone suggest? My code is mostly procedural.

推荐答案

您可以扩展PDO并添加同时执行以下操作的帮助程序方法:

You could extend PDO and add a helper method that does both:

class MyPDO extends PDO{

  public function prepareAndExecute($sql){

    // get all arguments passed to this function as an array
    $args = func_get_args();

    // drop first argument ($sql)
    array_shift($args);

    $stm = $this->prepare($sql);
    $stm->execute($args);

    return $stm;
  }

}

然后:

$results = $connection->prepareAndExecute(
  'UPDATE users SET f_name=?, l_name=?',
     $POST["first_name"],
     $_POST["last_name"]
);

($connection = MyPDO的实例)

这篇关于在程序环境中使用PDO的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:17
查看更多