2016-05-15 10 views
1

ここで私の更新機能はいくつかのパラメータを取って、整数や文字列であればそれらを評価し、クエリ文の値とスローに処理します。sqlとphp - このクエリやコードではアリの問題です

public function update ($table, $cols, $values, $addition) { 
    $db = $this->connect(); 
    $i = 0; 
    $update = ''; 
    if ((is_array($cols)) && (is_array($values))) { 
     foreach ($cols as $a) { 
      if (!is_int($values[$i])) { 
       $update = $a.'="'.$values[$i].'",'; 
      } else { 
       $update = $a.'='.$values[$i].','; 
      } 
      $i++; 
     } 
     $update = substr($update, 0, -1); 
    } else { 
     if (!is_int($values)) { 
      $update = $cols.'="'.$values.'",'; 
     } else { 
      $update = $cols.'='.$values.','; 
     } 
    } 
    echo "update ".$table." set ".$update." ".$addition."<br>"; 
    try { 
     $sql = $db->prepare("update ".$table." set ".$update." ".$addition); 
     $sql->execute(); 
    } catch (PDOException $e) { 
     print $e->getMessage(); 
    } 
    $db = null; 
} 

、ここでは、パラメータやSQLクエリ

$this->db->update("brands", "car_count", $brandCarCount[0]+1, "where brand = '".$brand."'"); 

update brands set car_count=2, where brand = 'alfa_romeo' 

私は本当に何が起こるかを理解していない、私は問題を見つけることができませんです。他の機能を選択または削除するためにも機能します。

私は助けが必要です!

+1

あなたはそこに余計なカンマを得た@Reto ffffffffffffffffffffffffffffffffffffffffff – Reto

+0

私はこの場所 – mjdcsy

+0

には問題を残していないだろう(ここで、前のもの)、時には我々は、木材理由を参照してくださいカント木の;) – Reto

答えて

1

末尾のカンマを削除し、関連するラインである:

$更新= RTRIM($更新、 '')。

と、これは完全なコードです:

public function update ($table, $cols, $values, $addition) { 
    $db = $this->connect(); 
    $i = 0; 
    $update = ''; 
    if ((is_array($cols)) && (is_array($values))) { 
     foreach ($cols as $a) { 
      if (!is_int($values[$i])) { 
       $update = $a.'="'.$values[$i].'",'; 
      } else { 
       $update = $a.'='.$values[$i].','; 
      } 
      $i++; 
     } 
    } else { 
     if (!is_int($values)) { 
      $update = $cols.'="'.$values.'",'; 
     } else { 
      $update = $cols.'='.$values.','; 
     } 
    } 
    $update = rtrim($update,','); 
    echo "update ".$table." set ".$update." ".$addition."<br>"; 
    try { 
     $sql = $db->prepare("update ".$table." set ".$update." ".$addition); 
     $sql->execute(); 
    } catch (PDOException $e) { 
     print $e->getMessage(); 
    } 
    $db = null; 
}