PDO bindParam into one statement?

前端 未结 5 1803
刺人心
刺人心 2020-12-02 19:14

Is there a way I can put these bindParam statements into one statement?

$q = $dbc -> prepare(\"INSERT INTO accounts (username, email, password) VALUES (:u         


        
5条回答
  •  生来不讨喜
    2020-12-02 19:57

    Personally, I prefer to use a wrapper function for all of pdo, which simplifies the code necessary substantially.

    For example, to run bound queries (well, all my queries), I do this:

    $iterable_resultset = query("INSERT INTO accounts (username, email, password) VALUES (:username, :email, :password)", array(':username'=>'bob', ':email'=>'bob@example.com', ':password'=>'bobpassword'));
    

    Note that not only is the sql simply a string, but it's actually a reusable string, as you can simply pass the sql as a string and change the array of variables to pass in if you want to perform a similar insert right after that one (not applicable to this situation, but applicable to other sql use cases).

    The code that I use to create this wrapper function is as below:

    /**
    * Run bound queries on the database.
    *
    * Use: query('select all from players limit :count', array('count'=>10));
    * Or: query('select all from players limit :count', array('count'=>array(10, PDO::PARAM_INT)));
    *
    * Note that it returns foreachable resultset object unless an array is specifically requested.
    **/
    function query($sql, $bindings=array(), $return_resultset=true) {
    DatabaseConnection::getInstance(); // Gets a singleton database connection
    $statement = DatabaseConnection::$pdo->prepare($sql); // Get your pdo instance, in this case I use a static singleton instance.  You may want to do something simpler.
    
    foreach ($bindings as $binding => $value) {
    if (is_array($value)) {
    $first = reset($value);
    $last = end($value);
    // Cast the bindings when something to cast to was sent in.
    $statement->bindParam($binding, $first, $last);
    } else {
    $statement->bindValue($binding, $value);
    }
    }
    
    $statement->execute();
    
    if ($return_resultset) {
    return $statement; // Returns a foreachable resultset
    } else {
    // Otherwise returns all the data an associative array.
    return $statement->fetchAll(PDO::FETCH_ASSOC);
    }
    }
    
    // Wrapper to explicitly & simply get a multi-dimensional array.
    function query_array($sql_query, $bindings=array()) {
    return query($sql_query, $bindings, false); // Set return_resultset to false to return the array.
    }
    

    As noted in the comments, you'd want to use your own method for setting up a database connection and getting an initialized pdo, but in general it allows your bound sql to be cut down to just a single line.

提交回复
热议问题