2013-03-15 70 views
0

我在Code Igniter模型中使用下面的代碼從數據庫中提取數據。但是,我的數據庫有2個Cust_Phone字段。我想設置它,以便當用戶輸入一個號碼電話字段進行搜索。我覺得有一種方法,使用像一個變量的多個字段的MySQL查詢

select distinct Phone from 
(SELECT Cust_Phone1 AS Phone 
    FROM Customer 

UNION 

SELECT Cust_Phone2 AS Phone 
    FROM Customer) as t where Phone <> '' 

在我的其他選擇查詢森那件事做到這一點在MySQL查詢,但我不知道該如何去這或如果我連這樣做的正確方法。

---笨型號功能---

public function customerQuery($First,$Last,$Zip,$Phone) { 
    $sql = "SELECT * FROM Customer WHERE Cust_First LIKE ? AND Cust_Last LIKE ? AND Cust_Zip LIKE ? AND Cust_Phone1 Like ?"; 
    if($First == null || $First == '') { 
     $First = '%'; 
    }else{ 
     $First = '%' . $First . '%'; 
    } 
    if($Last == null || $Last == '') { 
     $Last = '%'; 
    }else{ 
     $Last = '%' . $Last . '%'; 
    } 
    if($Zip == null || $Zip == '') { 
     $Zip = '%'; 
    }else{ 
     $Zip = '%' . $Zip . '%'; 
    } 
    if($Phone == null || $Phone == '') { 
     $Phone = '%'; 
    }else{ 
     $Phone = '%' . $Phone . '%'; 
    } 
    $query = $this->db->query($sql, array($First,$Last,$Zip,$Phone)); 
    return $query->result(); 
} 

回答

1

試試這個:

$sql = "SELECT * FROM Customer WHERE Cust_First LIKE ? AND Cust_Last LIKE ? AND Cust_Zip LIKE ? AND (Cust_Phone1 LIKE ? OR Cust_Phone2 LIKE ?)"; 
... 
... 
if($Phone == null || $Phone == '') { 
    $Phone = '%'; 
}else{ 
    $Phone = '%' . $Phone . '%'; 
} 
$query = $this->db->query($sql, array($First,$Last,$Zip,$Phone,$Phone)); 
0

你可以檢查,像這樣兩個手機領域......

$sql = "SELECT * FROM Customer WHERE Cust_First LIKE ? AND Cust_Last LIKE ? AND Cust_Zip LIKE ? AND (Cust_Phone1 Like ? OR Cust_Phone2 Like ?)"; 

... 

$query = $this->db->query($sql, array($First,$Last,$Zip,$Phone,$Phone));