duanlu1279 2016-02-29 01:16
浏览 83
已采纳

动态PDO查询中的整数值[重复]

This question already has an answer here:

I'm trying to use a dynamic PDO query (add where clause to the query if the variable is true) but i have a problem with integers values, this is my code:

$params = array();
$cond = array();

$query = "SELECT value FROM `table`";

if (!empty($firstname)) {
    $cond[] = "firstname = :fn";
    $params[':fn'] = $firstname;
}
if (!empty($lastname)) {
    $cond[] = "lastname = :ln";
    $params[':ln'] = $lastname;
}
if (count($cond)) {
    $query .= ' WHERE ' . implode(' AND ', $cond);
}

$query .= " LIMIT :min, :max";
$params[':min'] = $min; // INTEGER VALUE
$params[':max'] = $max; // INTEGER VALUE

$stmt = $db->prepare($query);
$stmt->execute($params);

The problem is that PDOStatement::execute treated all values as PDO::PARAM_STR and LIMIT need integer values.

I tried with PDOStatement::bindValue using PDO::PARAM_INT parameter but i don't know how to use it in a dynamic query.

</div>
  • 写回答

2条回答 默认 最新

  • doutuichan2681 2016-02-29 01:31
    关注

    You already have an array of keys and values to bind in $params, so after you prepare the statement, loop through it and bind accordingly:

    $params = array();
    $cond = array();
    
    $query = "SELECT value FROM `table`";
    
    if (!empty($firstname)) {
        $cond[] = "firstname = :fn";
        $params[':fn'] = $firstname;
    }
    if (!empty($lastname)) {
        $cond[] = "lastname = :ln";
        $params[':ln'] = $lastname;
    }
    if (count($cond)) {
        $query .= ' WHERE ' . implode(' AND ', $cond);
    }
    
    $query .= " LIMIT :min, :max";
    $params[':min'] = $min; // INTEGER VALUE
    $params[':max'] = $max; // INTEGER VALUE
    
    $stmt = $db->prepare($query);
    
    foreach($params as $key => $value)
    {
        if(is_int($value))
        {
            $stmt->bindValue($key, $value, PDO::PARAM_INT);
        }
        else
        {
            $stmt->bindValue($key, $value, PDO::PARAM_STR);
        }
    }
    
    $stmt->execute($params);
    

    Notice, that you must use bindValue, since bindParam will not work. The PHP manual states why:

    Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

    And once a foreach iteration is passed, $value no longer exists and can't be used as a reference. This is precisely the reason you must use bindValue

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP