2017-08-05 16 views
-3

我有一个方法在一个PHP类,使它从数据库中获取数据。此方法有3个参数,并且考虑到这些参数中的1,2或3个参数不为空,查询数据库的想法是。以下是上述方法:空参数到PHP类的方法

public function resultSearch($city = null, $price = null, $nr_dhomash = null){ 
     $db = new Database; 
     $stmt = ""; 

     if ($city != null && $price != null && $nr_dhomash !=null) { 
      $query = "Select * from postim where qyteti = :q and price <= :p and nr_dhoma=:n"; 
      $stmt = $db->connect()->prepare($query); 
      $stmt->bindParam(":q", $qyteti); 
      $stmt->bindParam(":p", $price); 
      $stmt->bindParam(":n", $nr_dhomash); 
     }else if ($city != null && $price !=null) { 
      $query = "Select * from postim where qyteti=:q and price <= :p"; 
      $stmt = $db->connect()->prepare($query); 
      $stmt->bindParam(":q", $qyteti); 
      $stmt->bindParam(":p", $price); 
     }else if ($city != null && $nr_dhomash !=null) { 
      $query = "Select * from postim where qyteti=:q and nr_dhoma=:n"; 
      $stmt = $db->connect()->prepare($query); 
      $stmt->bindParam(":q", $qyteti); 
      $stmt->bindParam(":n", $nr_dhomash); 
     }else if ($price != null && $nr_dhomash !=null) { 
      $query = "Select * from postim where price <= :p and nr_dhoma=:n"; 
      $stmt = $db->connect()->prepare($query); 
      $stmt->bindParam(":p", $price); 
      $stmt->bindParam(":n", $nr_dhomash); 
     }else if ($city != null) { 
      $query = "Select * from postim where qyteti=:q"; 
      $stmt = $db->connect()->prepare($query); 
      $stmt->bindParam(":q", $city); 
     }else if($price != null){ 
      $query = "Select * from postim where price <= :p"; 
      $stmt = $db->connect()->prepare($query); 
      $stmt->bindParam(":p", $price); 
     }else if ($nr_dhomash != null) { 
      $query = "Select * from postim where nr_dhoma=:n"; 
      $stmt = $db->connect()->prepare($query); 
      $stmt->bindParam(":n", $nr_dhomash); 
     } 
     $stmt->execute(); 
     $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 
     return $result; 
    } 

我不知道为什么如果2或所有参数不为空,此方法无法正常工作。有人可以帮忙吗?

+0

这是什么问题?你错了什么? –

+0

只有一个参数不为空,如果有2个参数不为空,或者所有3个参数都不为空,它才返回null,否则它的工作方式就好像只有一个参数不为null。 –

回答

1

所有这一切都可以简化为:

public function resultSearch($city = null, $price = null, $nr_dhomash = null){ 
    $db = new Database; 
    $stmt = ""; 
    $where = []; 
    $params = []; 

    if ($city != null) { 
     $where[] = 'qyteti = ?'; 
     $params[] = $city; 
    } 

    if ($price != null) { 
     $where[] = 'price <= ?'; 
     $params[] = $price; 
    } 

    if ($nr_dhomash != null) { 
     $where[] = 'nr_dhoma = ?'; 
     $params[] = $nr_dhomash; 
    } 

    $query = "Select * from postim"; 
    if ($where) { 
     $query .= ' where ' . implode(' and ', $where); 
    } 
    $stmt = $db->connect()->prepare($query); 
    $stmt->execute($params); 

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 
    return $result; 
} 
+0

这工作,是一个很好的解决方案,谢谢你u_mulder! –

相关问题