PDO Dynamic Query Building

后端 未结 2 1147
轮回少年
轮回少年 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.

    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.

提交回复
热议问题