gpt4 book ai didi

php - 仅在发布数据时显示 PDO BindParam

转载 作者:行者123 更新时间:2023-11-29 05:20:24 25 4
gpt4 key购买 nike

您好,这很可能是一个非常简单的答案,但我想知道如何仅在变量不为空时运行 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)) { } 中,但我不确定这是否是正确的方法,因为最终我想要添加多个搜索选项。

最佳答案

在这种情况下,我通常不会使用 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);

关于php - 仅在发布数据时显示 PDO BindParam,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26684661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com