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条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line