2014-10-31 57 views
1

你好,這很可能將是很簡單的答案,但我想知道如何運行BindParam只有當一個變量不低於空是一些示例代碼:只顯示PDO BindParam當數據發佈

// Adds variable name from input POST 
$post_status = filter_input(INPUT_POST, 'search_status', FILTER_SANITIZE_STRING); 
$post_firstname = filter_input(INPUT_POST, 'search_firstname', FILTER_SANITIZE_STRING); 

$query = 'SELECT * FROM candidate_information WHERE status = :status '; 

//Checks to see if post is empty 
if(!empty($post_firstname)) { 
    $query .= 'AND firstname LIKE :firstname'; 
    $post_firstname = '%'.$post_firstname.'%'; 
} 

$stmt_main_table = $db->prepare($query); 
$stmt_main_table->bindParam(':status', $post_status, PDO::PARAM_INT); 
// Need a way to only call bindParam if $post_firstname is not empty 
$stmt_main_table->bindParam(':firstname', $post_firstname, PDO::PARAM_STR); 

$stmt_main_table->execute(); 

我知道我總是可以將bindParam換成if(!empty($post_firstname)) { },但我不確定這是否是正確的方式,因爲我最終想添加多個搜索選項。

回答

3

我通常不會在這種情況下使用bindParam

相反,我填寫了必要的鍵值對的數組,併發送至​​:

$query = 'SELECT * FROM candidate_information WHERE status = :status '; 
$params = array(':status' => $post_status); 

//Checks to see if post is empty 
if(!empty($post_firstname)) { 
    $query .= 'AND firstname LIKE :firstname'; 
    $params[':firstname'] = '%'.$post_firstname.'%'; 
} 

// etc. 

$stmt_main_table = $db->prepare($query); 
$stmt_main_table->execute($params); 
+0

優秀@jeroen謝謝。不好意思問,但爲什麼不是所有事情都這樣完成,而不是BindParam? – 2014-10-31 23:15:04

+0

@JosephGregory我做的(差不多......)所有這些方式,無論是更容易/更短:-) – jeroen 2014-10-31 23:16:51

+0

哈哈非常感謝你:) – 2014-10-31 23:19:00