简体   繁体   English

如何使用PDO使准备工作在数据库查询中更有效?

[英]How to make the preparation more efficient in database query using PDO?

For example, I have a couple of tables in my database, eg, user, product, etc. Fro every table, I have at least an associated class with a couple of methods, such as addUser, updateUserName, updateUserPassword, etc. For every method, I need to prepare the SQL when using PDO, which looks like this: 例如,我的数据库中有几个表,例如,用户,产品等。对于每个表,我至少具有一个带有两个方法的关联类,例如addUser,updateUserName,updateUserPassword等。方法,使用PDO时需要准备SQL,如下所示:

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

Then I store the values in an array like this: 然后,将值存储在这样的数组中:

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

Then I use the PDO thing: 然后,我使用PDO:

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

So it seems that for all different methods inside the User class, I need to do this "prepare" thing. 因此,对于User类内部的所有不同方法,似乎都需要执行此“准备”操作。 Isn't it too tedious? 这不是很乏味吗? Is there a more efficient way to do so, especially the part where I store the values in an array considering there exist a table with many columns in which case I would end up with a very long prepare sentence? 有没有一种更有效的方法,尤其是考虑到存在一个包含许多列的表的情况下,我将值存储在数组中的部分会导致很长的准备语句呢?

Since Your own is insert and update try these 由于您自己是插入和更新,请尝试这些

        //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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM