dongshen6060 2018-08-07 09:27
浏览 63
已采纳

使用预准备语句构建PDO动态查询

i am basicly trying to update user information with a dynamic query.Everything good but when i try to execute query its return always false.

function updateUser($username, $email, $pass){

    $arr = [];
    $values = [];
    $params = [];

    if(isset($username))
    {
        array_push($arr, "userName = :username");
        array_push($values, $username);
        array_push($params, ":username");
    }
    if(isset($email))
    {
        array_push($arr, "userEmail = :email");
        array_push($values, $email);
        array_push($params, ":email");
    }
    if(isset($pass))
    {
        array_push($arr, "userPassword = :pass");
        array_push($values, $pass);
        array_push($params, ":pass");
    }

    $sql = "UPDATE users SET " . implode(", ", $arr) . " WHERE userId = :uId";
    $query = $db->prepare($sql);

    foreach ($params as $key) {
        foreach ($values as $value) {
            $query->bindValue($key, $value, PDO::PARAM_STR);
        }
    }

    $query->bindValue(":uId", $_SESSION["userId"]);

    if($query->execute() && $query->rowCount() > 0)
        return true;
    else
        return false // always false return
}

this is my array datas:

enter image description here

  • 写回答

1条回答 默认 最新

  • doumeng1089 2018-08-07 09:41
    关注

    this is funny. i can't answer my question. i found the solution. it is because of double foreach loop.

    $i = 0;
        foreach ($params as $key) {
            $query->bindValue($key, $values[$i], PDO::PARAM_STR);
        $i++;}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里