0

I would like to get data from MySQL database in json format and then print it to a PHP page.

I try to use this script:

<?php
    $page = $_GET['page'];
    $start = 0;
    $limit = 5;
    require_once('dbConnect.php');
    $total = mysqli_num_rows(mysqli_query($con, "SELECT id from photos"));
    $page_limit = $total/$limit;

    if($page<=$page_limit){
        $start = ($page - 1) * $limit;

        $sql = "SELECT * from photos limit $start, $limit";

        $result = mysqli_query($con,$sql);

        $res = array();

        while($row = mysqli_fetch_array($result)){
            array_push($res, array(
                "location"=>$row['location'],
                "image"=>$row['image'])
                );
        }
        echo json_encode($res);
    }else{
            echo "over";
    }

Database connection is OK, but it gives "over" message. Table contains 1 record, which details should be listed in JSON format.

1 Answer 1

3

$total is 1.

$limit is 5.

$page_limit is 1/5. (PHP will not cast to int).

$page is 1.

$page <= $page_limit is false.

To make your code work the way you're expecting, make $page_limit = ceil($total/$limit);.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.