fetchAll helper function using PDO

后端 未结 2 1007
小鲜肉
小鲜肉 2021-01-17 09:10

Suppose I have a function

function fetchAll(){
  $args = func_get_args();
  $query = array_shift($args);
  $query = str_replace(\"%s\",\"\'%s\'\",$query);
          


        
相关标签:
2条回答
  • 2021-01-17 09:55

    Every example I can find shows only how to bind parameters directly. Should I pass variable type as well as it's value? Or make this call always 4 lines - 3 binds and execute?

    You don't have to fire binds one line at a time; you can bind with an array like this:

    # the data we want to insert  
    $data = array('Cathy', '9 Dark and Twisty Road', 'Cardiff');  
    
    $STH = $DBH->("INSERT INTO folks (name, addr, city) values (?, ?, ?)");  
    $STH->execute($data); 
    
    0 讨论(0)
  • 2021-01-17 09:59

    edit: as the Colonel indicated, apparently this (no longer?) works with LIMIT clauses.


    If you're using simple queries / are not that bothered with type:

    function fetchAll(){
       $args = func_get_args();
       $query = array_shift($args);//'SELECT * FROM users WHERE status=? LIMIT ?,?'
       //you'll need a reference to your PDO instance $pdo somewhere....
       $stmt = $pdo->prepare($query);
       $stmt->execute($args);
       return $stmt->fetchAll();
    }
    
    0 讨论(0)
提交回复
热议问题