使用PDO进行多个条件查询

时间:2012-12-31 02:49:11

标签: php pdo

我在http://codereview.stackexchange.com中问了这个问题,他们希望我在这里发帖。我根本无法使用此代码。我从常规的mysql切换到更安全的pdo。有人能告诉我,我在这里失踪了。我几天都在苦苦挣扎,当我第一次搜索这个网站时,我能找到确切的答案。

  $input = $_POST['input'];
 $categories = $_POST['category'];
 $state = $_POST['state'];
 $zipcode = $_POST['zipcode']; 

$qq = $db->prepare(" SELECT * FROM classified  ")or die(print_r($qq->errorInfo(), true));
    /*** execute the prepared statement ***/
    $qq->execute();

    /*** echo number of columns ***/
    $rows = $qq->fetch(PDO::FETCH_NUM);
    if ($rows>0){
      $query = (" SELECT * FROM classified ");
   $cond = array();
   $params = array();

   if (!empty($input)) {
   $cond[] = "title = ?";
       $params[] = $input;
    }

   if (!empty($categories)) {
    $cond[] = "id_cat = ?";
    $params[] = $categories;
     }

    if (!empty($state)) {
    $cond[] = "id_state = ?";
    $params[] = $state;
    }    

   if (!empty($zipcode)) {
     $cond[] = "zipcode = ?";
     $params[] = $zipcode;
   }

  if (count($cond)) {
  $query .= ' WHERE  ' . implode(' AND ', $cond)or 
  die(print_r($query->errorInfo(),true));
 }

$stmt = $db->prepare($query);
 $stmt->execute($params);
 $ro = $stmt->fetch(PDO::FETCH_NUM);
   }
     if ($ro > 0) {
  foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) 
   {
     echo  $row['title'];
   echo  $row['categories'];
   echo  $row['state'];
   echo  $row['zipcode'];
  }
 } 

1 个答案:

答案 0 :(得分:1)

我认为在这里发布答案而不是发布链接是个好主意。我相信这对某些人有用。

    $input = $_POST['input'];
    $categories = $_POST['category'];
    $state = $_POST['state'];
    $zipcode = $_POST['zipcode'];

    $qq = $db->prepare(" SELECT * FROM classified  ")or die(print_r($qq->errorInfo(),
    true));
    /*** execute the prepared statement ***/
    $qq->execute();

/*** echo number of columns ***/
$rows = $qq->fetch(PDO::FETCH_NUM);
if ($rows>0){

 $query = " SELECT * FROM classified where confirm='0' ";  
 if(!empty( $_POST['input'])) {

 $query .= "AND title LIKE '%".$input."%' ";
 }


if (!empty($_POST['category']) )
   {
  $query .= "AND id_cat = ".$categories." ";

 }

  if (!empty($_POST['state']) )
  {
  $query .= "AND id_state = ".$state." ";

  }


  if(!empty($_POST['zipcode'])) {

  $query .= "AND zipcode = ".$zipcode." ";
  }
   $query .= "ORDER BY date ";

    }

   $stmt = $db->prepare($query);
  $stmt->execute($params);
   $result = $stmt->fetchAll();
 //  $ro = $stmt->fetch(PDO::FETCH_NUM);

  // it didn't work when I tried to count rows
 if ($result > 0) {
foreach ($result as $row)
 {
 echo  $row['title'];
 echo  $row['categories'];
 echo  $row['state'];
 echo  $row['zipcode'];
 }
 }else{
 echo " No data available";
   }