Dynamic bind with prepare()

Asked

Viewed 1,894 times

7

I am doing a function using PDO, when I try to use the PREPARE method the function does not end successfully, replace PREPARE with QUERY changing some arguments and worked.

But my question is this because 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);
  • 1

    You probably won’t have a field called "name,address,phone" in your table, but are trying to bind it. The syntax of bindValue is bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] ), you can’t pass a collection of fields like this.

  • 1

    You cannot bind column names only in values.

  • Hello Friends, but even if I try. Only Bind in the values is not right,

1 answer

7


The most practical way to make a dynamic bind is to count the number of queries pass it in sql and finally play the values in execute(). using Prepared statemens there is no need to escape the values with quotes. Remember to create a routine that validates/clears 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 up to you to pass the primary key(and its value) or not in the field/value array, if you pass it is always necessary to cut the zero Index of $camposand $values.

Simplified example

  • Dude, awesome. Thank you!

  • Hello @lost, your example really solved my problem and I could learn from it, but it didn’t work when I used the Excerpt $operation->execute($values); - Maybe because Execute expects to receive an array as argument aew when I put that chunk in place of that one worked, I put it like this - $operation->execute(array_values($data)); Am I right my friend? I had my doubts! Thank you.

  • Yes it expects an array, in the delete/update operation you can call it so $operacao->execute(array($id));. What are you right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.