PDO Dynamic Query Building

后端 未结 2 1136
轮回少年
轮回少年 2021-01-05 02:47

I have been old school using mysql_query and starting out now using PDO. Which is great!

But in my old scripts I had build a dynamic query builder, and i\'m having a

相关标签:
2条回答
  • 2021-01-05 03:39

    You'll need a separate $params parameter to your select method. I took the liberty of providing defaults for the method parameters. Like @userXxxx notes, you don't need a transaction just to do a SELECT.

    <?php
    
    class db {
    
        public $connection; //PDO
        public $dbFields; // This is an array of the fields plus VALUES
    
        public function select($where = '1', $params = array(), $limit = '', $fetchStyle = PDO::FETCH_ASSOC) { //fetchArgs, etc
            $fields = implode(', ', $this->dbFields);
    
            //create query
            $query = "SELECT $fields FROM {$this->table} WHERE $where $limit";
    
            //prepare statement
            $stmt = $this->connection->query($query);
    
            $stmt->execute($params);
    
            return $stmt->fetchAll($fetchStyle);
        }
    
        //...
    }
    
    
    $where = 'userId IN(:userId1, :userId2)';
    $params = array(':userId1' => 111, ':userId2' => 2222);
    $db->select($where, $params);
    

    Notes:

    • If you really want, you can add additional method parameters to match up with all the flexibility of PDOStatement::fetchAll.
    • I'm not sure what you mean about $dbFields being "fields plus VALUES". Can you explain?

    [Edit]

    You might want to take a look at the docs/examples for PDOStatement::execute, since that seemed to be where your confusion was rooted--in particular, the $input_parameters method parameter.

    0 讨论(0)
  • 2021-01-05 03:47

    What about this?

    public function select($where, $limit) {
        $query = "SELECT ". implode(", ", $this->dbFields) ." FROM ". $this->table." WHERE ". $where ." ". $limit."";
        $this->connection->query($query);
    }
    
    //Use what you had before:
    $results = $db->select("userId = 111 OR userId = 222");
    

    Not sure why you want to use transaction (for all-or-nothing basis or catching exceptions and rollback) or prepared queries (for sending multiple queries)...

    0 讨论(0)
提交回复
热议问题