我可以在SQL语句中绑定运算符吗?

时间:2018-02-12 13:52:32

标签: php mysql pdo

  

致命错误   未捕获的异常:'PDOException'

     

消息:'SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法出错;查看与您的MariaDB服务器版本对应的手册,以便在第3行''> ='''1000'附近使用正确的语法

<select name="operator1" class="form-control mr-sm-2">
                <option value="None">None</option>
                <option value=">="> >= </option>
                <option value="<="> <= </option>
            </select>

$user = User::searchUserBuiltQuery($_POST);
        var_dump($user);

    public static function searchUserBuiltQuery($data)
{
    $operator1  = $data['operator1'];
    $amount     = $data['amount'];
    $operator2  = $data['operator2'];
    $date       = $data['registration_date'];

    $sql = 'SELECT * from users 
            ';

    $db = static::getDB();

    if($operator1 != "None"){

        $sql .= "\n WHERE userBalance :operator1 :amount";

    }
    if($operator2 != "None"){

        $sql .= "\n WHERE user_registration_date :operator2 :date";

    }
    if($operator1 != "None" && $operator2 != "None"){

        $sql = "\n WHERE userBalance :operator1 :amount 
                    AND user_registration_date :operator2 :date";

    }

    $stmt = $db->prepare($sql);

    if($operator1 != "None"){

        $stmt->bindValue(':operator1', $operator1, PDO::PARAM_STR);
        $stmt->bindValue(':amount', $amount, PDO::PARAM_STR);
    }
    if($operator2 != "None"){

        $stmt->bindValue(':operator2', $operator2, PDO::PARAM_STR);
        $stmt->bindValue(':date', $date, PDO::PARAM_STR);
    }
    if($operator1 != "None" && $operator2 != "None"){

        $stmt->bindValue(':operator1', $operator1, PDO::PARAM_STR);
        $stmt->bindValue(':amount', $amount, PDO::PARAM_STR);
        $stmt->bindValue(':operator2', $operator2, PDO::PARAM_STR);
        $stmt->bindValue(':date', $date, PDO::PARAM_STR);
    }

    $stmt->setFetchMode(PDO::FETCH_CLASS, get_called_class());

    $stmt->execute();

    return $stmt->fetchAll();

}

1 个答案:

答案 0 :(得分:2)

  

$ sql。=“\ n WHERE userBalance:operator1:amount”;

您无法绑定运算符,因为数据库引擎需要它来创建语句。