user1805543
user1805543

Reputation:

How to count and auto create bindParams in pdo?

I am trying to create a function to auto create bindParams on function from Your Common Sence

Here PDO helper functions.

NOTICE : I know how to use function with executition, I am trying to use binds in it.

Here is the function how I am trying, This function calling to another function which counts and creates bindParams :

function insert($sql, $param_types, $args) {
    $stmt= $this->pdo->prepare($sql);
    $this->CreateParams($sql, $param_types, $args);
    $stmt->execute();
}

Here is the second function which will count and bind values :

function CreateParams($sql, $param_types $args) {
    $param_references[] = & $param_types;
    for($i=0; $i<count($args); $i++) {
        $param_references[] = & $args[$i];
    }
    call_user_func_array(array(
        $sql,
        'bindParam'
    ), $param_references);
}

This is the usaqe :

$sql = "INSERT INTO Auth_tokens (username, password_hash, selector_hash, expiry_date) values (?, ?, ?,?)";  
insert($sql, 'param_types', array($username, $random_password_hash, $random_selector_hash, $expiry_date));

I tried to use func_get_args(); in param but mixed it up totaly :(

Thanks

Upvotes: 0

Views: 215

Answers (1)

u_mulder
u_mulder

Reputation: 54841

You function can be simplified to:

function insert($sql, $param_types, $args) {
    $stmt= $this->pdo->prepare($sql);
    $stmt->execute($args);
}

As execute can use array of values as its argument. These values will be used in the query.

In this case $param_types argument is useless.

Update: still not clear what you expect, but code to start with is:

function insert($sql, $param_types, $args) {
    $stmt= $this->pdo->prepare($sql);
    $this->CreateParams($stmt, $param_types, $args);
    $stmt->execute();
}

function CreateParams($stmt, $param_types, $args) {
    $i = 0;
    foreach ($args as $argument) {
        $stmt->bindValue($i + 1, $argument, $param_types[$i]);
        $i++;
    }
}

// Calling as:

insert(
    'INSERT INTO Auth_tokens (username, password_hash, selector_hash, expiry_date) values (?, ?, ?, ?)', 
    [\PDO::PARAM_STR, \PDO::PARAM_STR, \PDO::PARAM_STR, \PDO::PARAM_STR], 
    [$username, $random_password_hash, $random_selector_hash, $expiry_date]
);

Upvotes: 1

Related Questions