【问题标题】:How to make the preparation more efficient in database query using PDO?如何使用 PDO 使数据库查询的准备工作更高效?
【发布时间】:2015-07-05 21:56:08
【问题描述】:

例如,我的数据库中有几个表,例如用户、产品等。对于每个表,我至少有一个关联的类和几个方法,例如 addUser、updateUserName、updateUserPassword 等. 对于每种方法,我在使用 PDO 时都需要准备 SQL,如下所示:

$sql = "INSERT INTO `user`
(`id`,`username`,`password`,`log`)
VALUES
(:id, :username, :password, :log)";

然后我将值存储在这样的数组中:

$array = array('id'=>$id, 'username'=>$username, 'password'=>$password, 'log'=>$log);

然后我使用 PDO 的东西:

$pdo = new PDO($dsn, $user, $password);
$mysql = $pdo->prepare($sql);
$mysql->execute($array);

所以看来,对于 User 类中的所有不同方法,我需要做这个“准备”的事情。是不是太乏味了?有没有更有效的方法来做到这一点,尤其是考虑到存在一个包含许多列的表时我将值存储在数组中的部分,在这种情况下我会得到一个很长的准备语句?

【问题讨论】:

  • 我很困惑为什么每个方法都需要这个,而不仅仅是一次
  • 我不太明白你所说的“只有一个”是什么意思。如果不同的方法需要准备不同的数组,也不一定所有的函数参数都需要准备在数组中,例如使用LIMIT $offset,$page_size查询时,这两个参数就不需要准备了。那么我将如何准备这些值呢?
  • 你在 OOP 方面装备精良吗,如果是,那么我认为单个 DB 类可以提供帮助
  • 好吧,这个问题说每个方法都插入相同,现在它不同 - 所以
  • 我了解 OOP 的概念,但我并不完全了解在 DB 类中究竟要做什么。你能更详细地解释一下吗?谢谢。

标签: php mysql sql pdo


【解决方案1】:

既然你自己是插入和更新试试这些

        //to query the database with prepared statements
    public function query ($sql, $parameters = array()) {

        //setting error to false to prevent interferance from previous failed queries
        $this->_error = false;

        //prepare SQL statement
        if ($this->_query = $this->_pdo->prepare ($sql)) {

            //checking to see whether any parameters were submitted along
            if (count($parameters)) {

                //setting the initial position for the binding values
                $position = 1;

                //getting the individual parameters and binding them with their respective fields
                foreach ($parameters as $param) {
                    $this->_query->bindValue ($position, $param);
                    $position++;
                }
            }
        }

        //executing the sql
        if ($this->_query->execute()) {
            //getting the number of rows returned
            $this->_count = $this->_query->rowCount();

            //keeping the results returned
            $this->_results = $this->_query->fetchAll (PDO::FETCH_OBJ);
        } else {
            $this->_error = true;
        }
        //returning all values of $this
        return $this;
    }


        //to insert data into a prescribed table
    public function insert ($table, $parameters = array()) {

        //checking if the $fields are not empty
        if (count($parameters)) {

            //making the keys of the array fields
            $fields = array_keys ($parameters);

            //creating the to-bind-values in the form (?, ?, ...)
            $values = '';
            $x = 1;

            foreach ($parameters as $field => $value) {

                //$value is different from $values
                $values .= '?';

                if ($x < count($parameters)) {
                    $values .= ', ';
                    $x++;
                }
            }
            //generating $sql
            $sql = "INSERT INTO `{$table}` (`".implode ('`, `', $fields)."`) VALUES ({$values})";

            //executing the sql
            if (!$this->query($sql, $parameters)->error()) {
                return true;
            }
        }
        return false;
    }

    //to update data in a prescribed table
    public function update ($table, $id = null, $parameters = array()) {

        //checking that $parameters is not an empty array
        if (count($parameters)) {
            $set = '';
            $x = 1;

            foreach ($parameters as $field => $value) {
                $set .= "`{$field}` = ?";

                if ($x < count($parameters)) {
                    $set .= ', ';
                    $x++;
                }
            }

            if ($id) {
                //generating query
                $sql = "UPDATE `{$table}` SET {$set} WHERE `id` = {$id}";
            } else {
                $sql = "UPDATE `{$table}` SET {$set} WHERE 1";
            }

            //executing the query
            if (!$this->query($sql, $parameters)->error()) {
                return true;
            }
        }
        return false;
    }

【讨论】:

  • 他在使用准备好的语句,你不是
  • 如果你真的不花时间阅读他/她的答案,它的哈希值就会给某人投票,这一点都不酷
  • 好朋友,我可以看到编辑历史,你完全改变了答案
  • 当你否决答案时我正在编辑,你甚至没有意识到 sql 正在调用一个名为 query 的函数
  • @GideonAppoh,感谢您的代码。这是一种更有效的方式还是实际上会损害查询效率(而不是编码时间)?
猜你喜欢
  • 2010-11-20
  • 1970-01-01
  • 2012-10-13
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 2013-06-15
  • 2013-11-05
  • 1970-01-01
相关资源
最近更新 更多