Dynamic Bind with prepare ()

6

I'm doing a function using the PDO, when I try to use the PREPARE method the function does not finish successfully, it replaces PREPARE with QUERY by changing some arguments and it worked.

But my question is the following because what with PREPARE is not working?

function create($tabela, array $dados){

    $campos = implode(", ", array_keys($dados));
    $values = "'".implode("', '", array_values($dados))."'";

    $pdo = new PDO('mysql:host=localhost;dbname=curso','root','');

    try{
        $operacao = $pdo->prepare("INSERT INTO $tabela (?) VALUES (?)");
        $operacao->bindValue(1,$campos);
        $operacao->bindValue(1,$values);
        $operacao->execute();
    }catch(PDOException $e){
        echo 'Erro '.$e->getMessage();
    }

    if($operacao->rowCount()>0){
        return true;
    }else{
        echo "Não Cadastrou";
    }

};

$evento = array('id_cliente' => 81, 'nome_cliente' => 'Marcos', 'idade' => 32);
create('clientes',$evento);
    
asked by anonymous 23.09.2014 / 05:23

1 answer

5

The most practical way to do a dynamic bind is to count the number of queries passed in the sql and finally to play the values at execute () . using prepared statemens you do not have to escape the values with quotation marks. Remember to create a routine that validates / cleans the table name and field lists to avoid unwanted results.

function create($tabela, array $dados){

    $campos = implode(", ", array_keys($dados));
    $values = implode(", ", array_values($dados));

    $totalInterrogacoes = count($dados);

    $interrogacoes = str_repeat('?,', $totalInterrogacoes);
    $interrogacoes = substr($interrogacoes, 0, -1); // remove a última virgula

    $sql = "INSERT INTO $tabela($campos) VALUES($interrogacoes)";
    $operacao = $pdo->prepare($sql);

    $operacao->execute($values);

}   

It is at your discretion to pass the primary key (and its value) or not in the field / values array, in case it is necessary to always cut the zero index of $campos and $values .

Simplified example

    
23.09.2014 / 06:03