How to make the variable id not repeat in the loop?

2

I am trying to get associative%% as argument of this methods, actually receive a array in the first argument and a numeric value in the second.

My question is how to make the array variable not repeat?

Well, you're giving this error:

  

Warning: PDOStatement :: execute () [pdostatement.execute]:   SQLSTATE [HY093]: Invalid parameter number: number of bound variables   does not match number of tokens in C: \ Program Files   (x86) \ EasyPHP-5.3.8.0 \ www \ connect \ standardModel.php on line 92

Source:

<?php
public function update($data = array(), $id)
{
    if (is_array($data) && count($data) > 0 && $id != false)
    {
        $sql = "update '{$this->table}' set ";

        foreach($data as $key => $value)
        {
            $sql .= $key . " = ?, ";
        }

        $sql = substr($sql, 0, - 2);
        $sql .= "where id = ?";

        $query = $this->db->prepare($sql);
        foreach($data as $value)
        {
            $query->bindValue($value . ",",$id);
        }

        if ($query->execute()) {
            return true;
        } else {
            return false;
        }
    }
}
?>
    
asked by anonymous 19.11.2014 / 18:53

2 answers

1

Well, I do not know if this will help you, but I've already done this once in the following way:

public static function update($tabela, $dados, $condicao = NULL){
    $sql = 'UPDATE '.$tabela.' SET ';
    foreach($dados as $key => $value):
        $campos[] = $key.'=?';
        $valores[] = $value;
    endforeach;
    $sql .= implode(', ', $campos);
    if(!is_null($condicao)) $sql .= ' WHERE '.$condicao;
    try{
        $query = self::$conexao->prepare($sql);
        $query->execute($valores);
    }catch(PDOException $e){
        self::erroLog(__FILE__, __FUNCTION__, $e->getMessage());
    }
}

Explaining:

$tabela I pass the table where the update will be done. $dados is my array that contains the data. $condicao is where I leave as null by default to update the entire table, in your case to update a specific id you can pass it as a parameter.

Ex:

update('tabelaCarros', $arrayDados, 'id=2');

Complete code in the GitHub

    
19.11.2014 / 19:21
1

This message appears when the query, when the number of columns is different from the values, is either more values and less columns or otherwise, in your code the way that requires least changes is to assign a% in% with% after sql assembly, a control variable id is required to enter the query number will match which value ( $data )

The changed code will look like this:

$sql = substr($sql, 0, - 2);
$sql .= " where id = ?";
$query = $this->db->prepare($sql);

$data['id'] = $id;
$i = 1; //indice atual da interrogação. 
foreach($data as $value)
{
   $query->bindValue($i, $value);
   $i++;
}

//simplificação sugerida pelo @Maniero
return $query->execute();
    
19.11.2014 / 21:56