mysql查询LIMIT使用属性:变量

时间:2017-08-31 12:27:24

标签: php mysql pdo

当我在查询中使用以下格式时,我收到语法错误或访问冲突。

$limit = $request->getAttribute('limit');
$sql = "SELECT * FROM users WHERE status = 1 ORDER BY date DESC LIMIT :limit";

 try{
    $db = new db();
    $db = $db->connect();
    $stmt = $db->query($sql);
    $stmt->bindParam(":limit", $limit);

    $users = $stmt->fetchAll(PDO::FETCH_OBJ);

    $db = null;

    if(empty($users)) {
        $response->getBody()->write
        ('
        {
            "error":
            {
                "message":"Invalid Request"
            }
        }');
    } else {
        $response->getBody()->write(json_encode($users));
    }
} catch(PDOException $e) {}

如何在查询中调用限制属性?

5 个答案:

答案 0 :(得分:3)

您需要执行以下操作(更改已注释): -

$limit = $request->getAttribute('limit');
$sql = "SELECT * FROM users WHERE status = 1 ORDER BY date DESC LIMIT :limit";

try{
    $db = new db();
    $db = $db->connect();
    $stmt = $db->prepare($sql); //prepare sql first
    $stmt->bindValue(':limit',(int)$limit,PDO::PARAM_INT);//tell value is integer
    $users = $stmt->fetchAll(PDO::FETCH_OBJ);

    if(count($users) ==0) {
        $response->getBody()->write('{"error":{"message":"No More Users Exist"}}');
    } else {
        $response->getBody()->write(json_encode($users));
    }
    $db = null;
} catch (PDOException $e) {
   print "Error!: " . $e->getMessage() . "<br/>";
   die();
}

答案 1 :(得分:2)

您看到的语法错误是因为当您bindParam()时,默认情况下PDO会将您的参数作为字符串插入,因此数据库引擎会看到LIMIT "10"之类的内容。

所以你有2个选择:你可以告诉PDO将值作为整数插入(参见@Alive to Die answer),或者更简单地说,你可以将它转换为整数并将其放在查询中。由于您首先进行投射,因此不存在SQL注入的风险:

$limit = (int) $request->getAttribute('limit');
$sql = "SELECT * FROM users WHERE status = 1 ORDER BY date DESC LIMIT $limit";

答案 2 :(得分:0)

最好使用prepare和execute语句,如:

$limit=10
$req=$db->prepare('SELECT * FROM users WHERE status = ? ORDER BY date DESC LIMIT ?');
$req->execute(array(1, $limit));

我从不使用bindParam语句。

答案 3 :(得分:0)

$limit变量简单地放入查询

$limit = $request->getAttribute('limit');
$sql = "SELECT * FROM users WHERE status = 1 ORDER BY date DESC LIMIT $limit";

答案 4 :(得分:0)

在PDO中将其定义为INT

$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);