Lesson 81 of 158 – Multiple Query Parameters
81%

Multiple Query Parameters

Multiple query parameters allow a REST API client to send several pieces of information in a single request. This is useful when a mobile application needs to combine search, filtering, sorting, pagination, or other options.

Note: Query parameters are written after ? in a URL. Multiple parameters are separated using &.

1. What are Query Parameters?

Query parameters are values added to the URL to provide additional information to an API.

GET /api/students.php?course=PHP

Here course is the query parameter and PHP is its value.

2. Multiple Query Parameters

More than one query parameter can be added to the same URL.

GET /api/students.php?course=PHP&status=active

There are two parameters:

  • course=PHP
  • status=active

3. Query Parameter Syntax

The general syntax is:

?parameter1=value1&parameter2=value2&parameter3=value3

The first parameter starts after ?. Every additional parameter starts after &.

4. Example with Three Parameters

GET /api/students.php
?course=PHP
&status=active
&page=1

This request contains three parameters:

  • Course
  • Status
  • Page number

5. Reading Multiple Parameters in PHP

$course =
    $_GET['course'] ?? '';

$status =
    $_GET['status'] ?? '';

$page = (int)(
    $_GET['page'] ?? 1
);

Each query parameter can be accessed independently using $_GET.

6. Trim Text Parameters

Text input should normally be cleaned of unnecessary whitespace.

$course = trim(
    $_GET['course'] ?? ''
);

$status = trim(
    $_GET['status'] ?? ''
);

7. Validate Required Parameters

An API can require certain parameters before processing the request.

if ($course === '') {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "Course is required"
    ]);

    exit;
}

8. Multiple Filters

Multiple query parameters are very useful for filtering records.

GET /api/students.php
?course=PHP
&status=active

The SQL query can apply both conditions:

SELECT *
FROM students
WHERE course = ?
AND status = ?

9. Search and Filter Together

Search and filtering can be combined in one API request.

GET /api/students.php
?search=rahul
&course=PHP

The API can search for Rahul while restricting the results to PHP students.

10. Search, Filter and Pagination

GET /api/students.php
?search=rahul
&course=PHP
&page=1
&limit=10

This request can provide:

  • Search keyword
  • Course filter
  • Page number
  • Number of records per page

11. Add Sorting Parameter

Sorting can also be added to the same request.

GET /api/students.php
?search=rahul
&course=PHP
&status=active
&sort=name
&order=asc

This gives the API several instructions in one request.

12. Build SQL Conditions Dynamically

When optional parameters are supported, the API can build the WHERE conditions according to the parameters received.

$conditions = [];
$params = [];

if ($course !== '') {

    $conditions[] =
        "course = ?";

    $params[] = $course;
}

if ($status !== '') {

    $conditions[] =
        "status = ?";

    $params[] = $status;
}

13. Combine Conditions with AND

$where = '';

if (!empty($conditions)) {

    $where =
        'WHERE ' .
        implode(
            ' AND ',
            $conditions
        );
}

This creates a dynamic WHERE clause using only the conditions that were supplied.

14. Prepare the SQL Query

$sql = "
    SELECT
        id,
        student_id,
        name,
        course,
        status
    FROM students
    $where
    ORDER BY id DESC
";

The values remain separate from the SQL statement.

15. Execute with Multiple Parameters

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

$stmt->execute($params);

$students =
    $stmt->fetchAll(
        PDO::FETCH_ASSOC
    );

PDO binds the supplied values to the prepared statement placeholders.

16. Complete Multiple Parameter API

<?php

header(
    "Content-Type: application/json"
);

require_once '../db.php';

$search = trim(
    $_GET['search'] ?? ''
);

$course = trim(
    $_GET['course'] ?? ''
);

$status = trim(
    $_GET['status'] ?? ''
);

$page = (int)(
    $_GET['page'] ?? 1
);

$limit = (int)(
    $_GET['limit'] ?? 10
);

$page = max(
    1,
    $page
);

$limit = max(
    1,
    min($limit, 100)
);

$offset =
    ($page - 1) * $limit;

$conditions = [];
$params = [];

if ($search !== '') {

    $conditions[] = "
        (
            name LIKE ?
            OR student_id LIKE ?
        )
    ";

    $keyword =
        "%{$search}%";

    $params[] = $keyword;
    $params[] = $keyword;
}

if ($course !== '') {

    $conditions[] =
        "course = ?";

    $params[] = $course;
}

if ($status !== '') {

    $conditions[] =
        "status = ?";

    $params[] = $status;
}

$where = '';

if (!empty($conditions)) {

    $where =
        "WHERE " .
        implode(
            " AND ",
            $conditions
        );
}

try {

    $sql = "
        SELECT
            id,
            student_id,
            name,
            course,
            status
        FROM students
        $where
        ORDER BY id DESC
        LIMIT ? OFFSET ?
    ";

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

    $position = 1;

    foreach ($params as $value) {

        $stmt->bindValue(
            $position,
            $value,
            PDO::PARAM_STR
        );

        $position++;
    }

    $stmt->bindValue(
        $position,
        $limit,
        PDO::PARAM_INT
    );

    $position++;

    $stmt->bindValue(
        $position,
        $offset,
        PDO::PARAM_INT
    );

    $stmt->execute();

    $students =
        $stmt->fetchAll(
            PDO::FETCH_ASSOC
        );

    echo json_encode([
        "success" => true,
        "page" => $page,
        "limit" => $limit,
        "data" => $students
    ]);

} catch (PDOException $e) {

    http_response_code(500);

    echo json_encode([
        "success" => false,
        "message" =>
            "Server error"
    ]);
}

?>

17. Multiple Parameters in Postman

In Postman, you can enter query parameters using the Params section.

Key Value
search rahul
course PHP
status active
page 1
limit 10

18. Multiple Parameters in URL

The same Postman request can be represented as a complete URL:

http://localhost/api/students.php?search=rahul&course=PHP&status=active&page=1&limit=10

The ? starts the query string and & separates parameters.

19. React Native Fetch with Multiple Parameters

const search = "rahul";
const course = "PHP";
const status = "active";
const page = 1;
const limit = 10;

const url =
    "https://example.com/api/students.php"
    + "?search="
    + encodeURIComponent(search)
    + "&course="
    + encodeURIComponent(course)
    + "&status="
    + encodeURIComponent(status)
    + "&page="
    + page
    + "&limit="
    + limit;

const response =
    await fetch(url);

const result =
    await response.json();

console.log(result.data);

20. Axios Params Object

Axios provides a convenient way to send multiple query parameters.

const response = await axios.get(
    "https://example.com/api/students.php",
    {
        params: {
            search: "rahul",
            course: "PHP",
            status: "active",
            page: 1,
            limit: 10
        }
    }
);

console.log(
    response.data.data
);

21. Query Parameters with Optional Values

Not every parameter needs to be mandatory. For example, the user may select a course but not select a status.

GET /api/students.php
?course=PHP
&page=1
&limit=10

The PHP API should apply only the filters that were provided.

22. Validate Numeric Parameters

$page = filter_input(
    INPUT_GET,
    'page',
    FILTER_VALIDATE_INT
);

if ($page === false ||
    $page === null) {

    $page = 1;
}

Numeric parameters such as page numbers should be validated before they are used.

23. Validate Allowed Filter Values

$allowedStatus = [
    "active",
    "inactive"
];

if (
    $status !== '' &&
    !in_array(
        $status,
        $allowedStatus,
        true
    )
) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid status"
    ]);

    exit;
}

Allowing only known values makes the API easier to control and predict.

24. Multiple Parameters with Sorting

Search, filters, pagination, and sorting can all be combined.

GET /api/students.php
?search=rahul
&course=PHP
&status=active
&sort=name
&order=asc
&page=1
&limit=10

This type of API request is common in real-world mobile applications.

25. Query Parameters and SQL Injection

Query parameters come from the client and must never be blindly added to an SQL statement.

Unsafe:

$sql =
    "SELECT *
     FROM students
     WHERE course = '$course'";

Safer:

$stmt = $pdo->prepare(
    "SELECT *
     FROM students
     WHERE course = ?"
);

$stmt->execute([
    $course
]);

26. Multiple Parameters and Authentication

Multiple query parameters do not replace authentication. If the API contains private data, authentication should still be applied.

Authorization:
Bearer YOUR_JWT_TOKEN

The API can verify the JWT before processing the requested filters, search, sorting, or pagination.

27. Complete Request Flow

React Native
     ↓
User Selects Filters
     ↓
Search + Course + Status
     ↓
Page + Limit
     ↓
GET Request
     ↓
PHP REST API
     ↓
Validate Parameters
     ↓
Build SQL Conditions
     ↓
Prepared Statement
     ↓
MySQL
     ↓
JSON Response
     ↓
FlatList

28. Test Multiple Parameters in Postman

Method: GET

http://localhost/api/students.php?search=rahul&course=PHP&status=active&page=1&limit=10

Click Send.

The API should return only records that satisfy the supplied conditions and belong to the requested page.

29. Real Mobile App Example

Consider a student management application. The user wants to find active PHP students whose name contains "rahul", sorted alphabetically, with 10 records per page.

GET /api/students.php
?search=rahul
&course=PHP
&status=active
&sort=name
&order=asc
&page=1
&limit=10

This single request can provide all the information needed by the student list screen.

30. Multiple Query Parameters Summary

Multiple query parameters allow a REST API to receive several options in one request. They are especially useful for combining search, filtering, sorting, and pagination in a React Native application.

GET /api/students.php
?search=rahul
&course=PHP
&status=active
&sort=name
&order=asc
&page=1
&limit=10

The server should validate the parameters, use prepared statements for database values, safely handle dynamic sorting, and return a clear JSON response.

📌 Key Points

  • Multiple query parameters allow several values in one API request.
  • The first query parameter starts after ?.
  • Additional parameters are separated using &.
  • PHP can read query parameters using $_GET.
  • Search, filtering, sorting, and pagination can be combined.
  • Optional parameters can be processed only when they are supplied.
  • Numeric parameters should be validated.
  • Allowed filter values should be checked.
  • Database values should be handled using prepared statements.
  • Dynamic sort columns should use an allowlist.
  • Multiple query parameters do not replace authentication.
  • React Native Fetch and Axios can send multiple query parameters.
  • Postman can be used to test complex API URLs.
  • The next lesson will cover API validation.

🧠 Quick Quiz

Question: Which symbol is used to separate multiple query parameters in a URL?