1

我在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'];
  }
 } 
4

1 回答 1

1

I think it's a good idea to post an answer here rather than posting a link. I'm sure it will be useful for some people.

    $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";
   }
于 2012-12-31T16:39:07.170 回答