仅在发布数据时显示PDO BindParam

时间:2014-10-31 23:05:21

标签: php mysql 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)) { }中,但我不确定这是否是正确的方式,因为我最终想要添加多个搜索选项。

1 个答案:

答案 0 :(得分:3)

我通常不会在这种情况下使用bindParam

相反,我使用必要的键值对填充数组并将其发送到execute()

$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);