2010-11-01 68 views
1

所以這是我當前的代碼:更好的方法來做到這一點?

function addPage($uniquename, $ordernum, $title, $author, $content, $privilege, $description=NULL, $keywords=NULL){ 
    if (!$description) $description = NULL; 
    if (!$keywords) $keywords = NULL; 
    //UPDATE `table` SET `ordernum` = `ordernum` + 1 WHERE `ordernum` >= 2 
    $query = "UPDATE ".$this->prefix."page SET ordernum = ordernum+1 WHERE ordernum >= ?"; 
    if ($stmt = $this->db->prepare($query)){ 
     $stmt->bind_param("i", $ordernum); 
     $stmt->execute(); 
     if (!arCheck($stmt)) return false; 
    } else { 
     $this->stmtError("addPage", $stmt->error); 
    } 

    $query = "INSERT INTO ".$this->prefix."page VALUES (LCASE(?), ?, ?, ?, ?, ?, ?, ?)"; 
    if ($stmt = $this->db->prepare($query)){ 
     $stmt->bind_param("sisisssi", $uniquename, $ordernum, $title, $author, $content, $description, $keywords, $privilege); 
     $stmt->execute(); 
     return arCheck($stmt); 
    } else { 
     $this->stmtError("addPage", $stmt->error); 
    } 
} 

它是假設一個新的頁面添加到數據表。 MySQL是由Phil Hunt提供的Store the order of something in MySQL

我知道你可以使用多重查詢來完成同樣的事情,但是我被告知準備好的語句在性能和安全性方面更好。有沒有另一種方法來做到這一點?像準備好的多重查詢?

另外,如何做交易?我不完全確定這是什麼,我假設它是,如果我們說,INSERT語句失敗,它也會撤消UPDATE語句?

注意:arCheck函數將關閉語句。

+0

當你的功能需要比3至5個參數更多的時候,它就是一種代碼味道。您可能想要爲所有不同的內容項目使用數組。另一種代碼異味是大括號的不一致使用。我建議始終使用它們。 – markus 2010-11-01 05:51:57

回答

0

至少在大多數情況下,重複查詢的準備語句確實更快。它們也更安全,因爲它們會自動轉義輸入值,防止SQL注入攻擊。如果你想在PHP中使用它們,你需要MySQLi extension

您似乎對交易有正確的想法。使用MySQLi有commitrollback方法,否則可以使用mysql_query("COMMIT")mysql_query("ROLLBACK")

+0

那麼我的做事方式會好嗎? – Pwnna 2010-11-01 18:15:08

相關問題