2012-11-12 44 views
0

我正在使用以下代碼從MySQL表中選擇數據。有人能告訴我如何改善這一點,因爲它似乎有點凌亂?改進我使用PDO和添加更新語句的SELECT

此外,我需要運行一個UPDATE語句來增加「視圖」列中的值,每次從數據庫中查詢客戶時。數據庫中的每個客戶行都有一個名爲「views」的列。例如,ABC Corp有100個視圖。如果我搜索ABC Corp並且數據庫返回記錄,則此記錄的「視圖」列應該更新爲101.執行此操作的最佳方法是什麼?

if ($search && ($group && $group !== "*")) { 
    $sql = "SELECT * FROM customers WHERE description LIKE :description AND groupId LIKE :groupId"; 
    $result = $conn->prepare($sql); 
    $result->bindValue(":description", "%" . $search . "%", PDO::PARAM_STR); 
    $result->bindValue(":groupId", $groupId, PDO::PARAM_INT); 
} else if ($search) { 
    $sql = "SELECT * FROM customers WHERE description LIKE :description"; 
    $result = $conn->prepare($sql); 
    $result->bindValue(":description", "%" . $search . "%", PDO::PARAM_STR); 
} else if ($group !== "*") { 
    $sql = "SELECT * FROM customers WHERE groupId LIKE :groupId"; 
    $result = $conn->prepare($sql); 
    $result->bindValue(":groupId", $groupId, PDO::PARAM_INT); 
} else { 
    $sql = "SELECT * FROM customers"; 
    $result = $conn->prepare($sql); 
} 

回答

2

如何這樣的事情,

$sql = "SELECT * FROM customers "; 
$and = $grp = FALSE; 

if($search || ($group && $group !== "*") { 
$sql .= " WHERE "; 
if ($search) { 
    $sql .= " description LIKE :description "; 
    $and = TRUE; 
} 

if ($group && $group !== "*") { 
    if($and === TRUE) 
    $sql .= " AND ";   
    $sql .= " groupId LIKE :groupId "; 
    $grp = TRUE;  
}  
} 

$result = $conn->prepare($sql); 
if($and === TRUE) 
    $result->bindValue(":description", "%" . $search . "%", PDO::PARAM_STR); 

if($grp === TRUE) 
    $result->bindValue(":groupId", $groupId, PDO::PARAM_INT); 

對於UPDATE聲明,

//say $cust_name is the requested customer to be searched 
    $sql = "SELECT views from customers where customer_name = '" $cust_name."'"; 
    $res = $conn->query($sql); 
    $views = $res->fetchColumn() + 1; 
    //sets 'views' to num_of_customers/rows returned. 
    $sql = "UPDATE customers SET VIEWS = " .$views." WHERE customer_name = '" $cust_name."'"; 
    $res = $conn->query($sql); 
+0

感謝。如何將UPDATE語句添加到它? – Zoolander

+0

當你指'每次查詢客戶時',你的意思是'SELECT'查詢,包括'groupId LIKE:groupId'? –

+0

我的意思是任何時候在SELECT語句中返回「customer」行。 (即SELECT * FROM customers)。 – Zoolander