<?php

header('Access-Control-Allow-Origin:*');

function getXhprofInfoList() {

    $option = $_GET['option'] ?? "";

    // 分页
    // $pageIndex = $_GET['pageIndex'];
    // $pageSize  = $_GET['pageSize'];

    $pageIndex = $_GET['pageIndex'] ?? 1;
    $pageSize = $_GET['pageSize'] ?? 10;

    $pageBegin = ($pageIndex-1)*$pageSize;

    $mysql = new mysqli("192.168.0.24", 'root', '(M12JI237^&1', 'xhprof', '3306');
    if($mysql->connect_errno) {
        dir($mysql->connect_error);
    }

    $sql = "select * from xhprof_data ";
    if ($option != ''){
        $arr = explode(',', $option);
        // var_dump($arr);
        // exit;
        $sql .= ' where ';
        foreach($arr as $k) {
            if(strpos($k, '>=') !== false) {
                $t = explode('>=', $k);
                $sql .= $t[0] . ">='" .$t[1] . "'". " and ";
            }else if(strpos($k, '<=') !== false) {
                $t = explode('<=', $k);
                $sql .= $t[0] . "<='" .$t[1] . "'". " and ";
            }else if(strpos($k, '!=') !== false) {
                $t = explode('!=', $k);
                $sql .= $t[0] . "!='" .$t[1] . "'". " and ";
            }else if(strpos($k, '>') !== false) {
                $t = explode('>', $k);
                $sql .= $t[0] . ">'" .$t[1] . "'". " and ";
            }else if(strpos($k, '<') !== false) {
                $t = explode('<', $k);
                $sql .= $t[0] . "<'" .$t[1] . "'". " and ";
            }else if(strpos($k, '=') !== false) {
                $t = explode('=', $k);
                $sql .= $t[0] . "='" .$t[1] . "'". " and ";
            }
        }

        $sql = substr($sql, 0, strrpos($sql, 'and'));
    }


    $sql .= " order by unix desc";
    $sql .= " limit " . $pageBegin . "," . $pageSize . ";";
    // echo $sql;
    $res = $mysql->query($sql);

    // 总条数
    $sqlCount = "select count(*) as total from xhprof_data";
    $count = $mysql->query($sqlCount);
    $total = (int)$count->fetch_assoc()['total'];

    if ($res && $res->num_rows) {
        $res->data_seek(0);
        while($row = $res->fetch_assoc()) {
            $data[] = $row;
        }
        $res = array(
            "code" => "0000",
            "data" => [
                "list" => $data,
                "total" => $total
            ]
        );
        $mysql->close();
        echo json_encode($res);
    } else {
        $mysql->close();
    }
}
getXhprofInfoList();


