PHP以JSON格式打印SQL查询


PHP print SQL query in JSON format

我想以json格式从MySQL数据库中获取数据,然后将其打印到PHP页面。

我尝试使用这个脚本:

<?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";
    }

数据库连接正常,但会发出"结束"消息。表中包含1条记录,详细信息应以JSON格式列出。

$total为1。

CCD_ 6为5。

CCD_ 7为1/5。(PHP不会强制转换为int)。

CCD_ 8为1。

$page <= $page_limit为false。

要使代码按预期方式工作,请制作$page_limit = ceil($total/$limit);