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


How to get rest api output the number of row imputed on the url

我创建了一个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() .'}}'; 
    }
}

你将不得不改变你的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() .'}}'; 
    }
}

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

读取变量中的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() .'}}'; 
    }
}