如何获取rest api输出在url上输入的行数

时间:2015-08-29 10:34:50

标签: php mysql angularjs slim

我创建了一个REST API,如果我像http://api.randomuser.me/?results=20那样访问API,我就想要输出20行(例如)。

这是我的PHP代码。我是Slim和AngularJS的新手,请帮忙。

function getUsers() {
    $sql = "select * FROM user";
    try {
        $db = getConnection();
        $stmt = $db->query($sql);  
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($users);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

提前致谢。

2 个答案:

答案 0 :(得分:0)

读取变量中的results参数,并在LIMIT子句中使用它而不是硬编码10

function getUsers() {

    try {
        $db = getConnection();

        $limit = $_GET["results"];
        // validate $limit for valid value here and continue only if  
        // using something like 
        // $limit = $db->real_escape_string($limit);
        // and continue only if successfully validated

        $sql = "select * FROM user ORDER BY id LIMIT ".(strlen($limit) ? $limit : 10);
        $stmt = $db->query($sql);  
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($users);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

答案 1 :(得分:0)

你必须改变你的sql ......比如



$limit = $_GET['limit'];
/clean your input make sure it has a value using isset,empty etc
$sql = "select * FROM user ORDER BY id LIMIT ".$limit; //this is a quick example rather use pdo bound parameters.
    try {
        $db = getConnection();
        $stmt = $db->query($sql);

        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($users);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}




请记住清理输入并在查询中使用绑定参数。