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

リンクを投稿するのではなく、ここに回答を投稿することをお勧めします。一部の人にとっては役立つと確信しています。

    $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 に答える