简体   繁体   中英

PHP print SQL query in JSON format

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.

$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); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM