2017-05-05 43 views
0

我想寫基於傑弗裏的INSERT查詢上laracast寫一個可重複使用的更新查詢在PHP

這在PHP中的可重複使用的更新查詢是傑夫的插入查詢

public function insert($table, $parameters) 
{ 
$sql = sprintf(
     'INSERT INTO %s (%s) VALUES (%s)', 
     $table, 
     implode(', ', array_keys($parameters)), 
     ':' . implode(', :', array_keys($parameters)) 

    ); 
    try { 
     $statement = $this->pdo->prepare($sql); 
     $statement->execute($parameters); 
    } catch (Exception $exception) { 
     die("Something Went Wrong"); 
    } 
} 

這是更新的代碼我想寫

public function update($table, $parameters, $Condition) 
{ 
    $sql = sprintf(
     'UPDATE %s SET %s=%s WHERE ' . $Condition, 
     $table, 
     implode('=,', array_keys($parameters)) 
     , 
     ':' . implode(', :', array_keys($parameters)) 

    ); 


    try { 
     $statement = $this->pdo->prepare($sql); 
     $statement->execute($parameters); 
    } catch (Exception $exception) { 
     die("Something Went Wrong"); 
    } 

} 

我希望把它作爲可重複使用的插入查詢被剛好路過的數據

所有幫助高度appricated

+0

不知道我理解。您可以將語句保存爲類實例的成員,並在只有相同參數和值的情況下再次使用它,那麼您只需要再次執行語句,但使用不同的參數 –

+3

請注意,[您的代碼易受攻擊SQL注入(https://phpdelusions.net/pdo/sql_injection_example) –

+0

@AlonEitan它不是一個聲明,但一個功能,他希望重用 –

回答

0

這是一個真的不好主意。不要這樣做。

相反,我會建議爲你的實體創建自定義data mappers,將載有手工製作的SQL,用正確綁定參數/值。

但作爲一個實驗,這是我想出了:

public function update($table, $parameters, $conditions) 
{ 
    $sql = sprintf(
     'UPDATE %s SET %s WHERE %s', 
     $table, 
     implode(', ',array_map(
      function ($key) { 
       return "{$key} = :s_{$key}"; 
      }, 
      array_keys($parameters) 
     )), 
     implode(' AND ',array_map(
      function ($key) { 
       return "{$key} = :w_{$key}"; 
      }, 
      array_keys($conditions) 
     )) 
    ); 

    $parameters = array_combine(
     array_map(function($key){ return ":s_{$key}"; }, array_keys($parameters)), 
     $parameters 
    ) + array_combine(
     array_map(function($key){ return ":w_{$key}"; }, array_keys($conditions)), 
     $conditions 
    ); 

    try { 
     $statement = $this->pdo->prepare($sql); 
     $statement->execute($parameters); 
    } catch (Exception $exception) { 
     die("Something Went Wrong"); 
    } 

} 

請記住,是你的「用戶」能以某種方式影響鍵或者$parameters$conditions陣列,那麼這代碼容易受到SQL注入攻擊。

P.S.
在你原來的例子,你有$Condition參數簡單地串聯到您的查詢的末尾。這會造成SQL注入攻擊的巨大風險。