2012-12-31 94 views
1

我在http://codereview.stackexchange.com問了這個問題,他們想讓我把它發佈在這裏。我無法得到這個代碼工作。我從普通的mysql切換到更安全的pdo。有人能告訴我我在這裏錯過了什麼嗎?我一直在努力掙扎幾天,當我第一次搜索這個網站時,我可以找到確切的答案。使用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

清理示例中的空白。每個人都可以更輕鬆地解析,追蹤並最終找出問題所在。 – hafichuk

+0

3個問題:它應該做什麼?它怎麼不起作用?你有錯誤消息要分享嗎? – HorusKol

+1

看起來像在'$ query'上調用'errorInfo()',它實際上只是一個SQL字符串。你是否啓用了error_reporting?如果是這樣,你會看到至少一個重大的錯誤。 '的error_reporting(E_ALL); ini_set('display_errors',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"; 
    }