2016-10-04 93 views
2

我想研究如何準備語句在MySQL中工作,我被告知,我使用的所有代碼都容易受到MySQL注入,我使用codeigniter php模型來編寫這樣的mysql查詢代碼例如。轉換爲mysql準備語句

public function getOpenLoans($id){ 
      $query = 'select a.Amount as OpenLoanAmount , a.monthly_amortization as totalInstallment 
         from useropenloan a 
         where a.Owner = ' .$id. ' and UPDATE_DT is null' ; 

      $query = $this->db->query($query); 
      $result = $query->result(); 
      return $result; 
     } 

這基本上得到一排的一些信息,但是我真正想知道的是如何 其轉換爲準備MySQL的說法,我想下面的計算器不同的方法和一些YouTube的教程,但他們不工作,所以有人可以幫助我在準備好的sql語句中編寫這段代碼。

我嘗試了這種方式

$stmt = $conn->prepare(select a.Amount as OpenLoanAmount , a.monthly_amortization as totalInstallment 
          from useropenloan a 
          where a.Owner = :id and UPDATE_DT is null); 
$stmt->bindParam(':id', $id); 
$stmt->execute(); 
+0

你有周圍的SQL報價? – danopz

+0

@copynpaste在第二準備(選擇...)不,我沒有使用任何引號 – FaF

+0

添加它們,這只是一個字符串 – danopz

回答

1
public function getOpenLoans($id){ 
    $sql = "select a.Amount as OpenLoanAmount , a.monthly_amortization as totalInstallment from useropenloan a where a.Owner = ? and UPDATE_DT is null"; 
    $query = $this->db->query($sql, array($id)); 
    $result - $query->result(); 
    return $result; 
} 
+0

Koning,我使用codeigniter,所以它出於某種原因停在$ conn,所以我應該使用$ this-> db-> prepare? – FaF

+0

我使用了$ conn是現有PDO連接的假設。有關如何設置的詳細信息,請參閱http://php.net/manual/en/pdo.connections.php。 – Koning

+0

這是我如何執行舊查詢 $ query = $ this-> db-> query($ query); $ result = $ query-> result(); 返回$結果; ,所以它必須是差異化的方式嗎? – FaF