代码之家  ›  专栏  ›  技术社区  ›  David

PHP返回空数组,MySQL返回集合

  •  0
  • David  · 技术社区  · 5 年前

    我在phpMyAdmin中直接运行SQL代码与使用PHP的PDO之间存在差异。这是我的PHP代码:

    <?php
        $configs_database = include(dirname( __DIR__, 2) . '/php/config_database.php');
    
        // Database variables
        $dbHost = $configs_database['host'];
        $dbUsername = $configs_database['username'];
        $dbPassword = $configs_database['password'];
        $dbName = $configs_database['name'];
    
        /* Create connection */ 
        $dsn = "mysql:dbname=$dbName;host=$dbHost;charset=utf8mb4";
        $db = new PDO($dsn, $dbUsername, $dbPassword);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
    
        // Get the business information where the user_id equals the session value
        $stmt = $db->prepare("
            SELECT
                customer.*
            FROM
                customer
            WHERE
                customer.business_id = (SELECT business_id FROM `user` WHERE user_id = :userId)
            LIMIT :limit
            OFFSET :offset;");
    
        // Parameterize the query
        $userId = ($_POST["userId"] ? $_POST["userId"] : $_SESSION["id"]);
        $limit = ($_POST["rowCount"] ? $_POST["rowCount"] : 99999);
        $offset = ($_POST["current"] && $_POST["rowCount"] ? intval($_POST["current"]) * $_POST["rowCount"] : 0);
        $stmt->bindValue(':userId', $userId, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    
        // Execute the query
        $stmt->execute();
    
        // Explicitly close the connection
        $db = null;
    
        // Get the results
        $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        echo json_encode($customers);
        return json_encode($customers);
    ?>
    

    如果我在失眠时提交请求,并使用以下JSON:

    {
        "userId": 2,
        "current": 1,
        "rowCount": 100
    }
    

    它打印一个空数组。但是,如果我直接在phpMyAdmin中运行SQL,它将返回预期的集合。我甚至不知道如何调试它,因为如果我回显以下值 $userId , $limit ,以及 $offset (我在参数中传递的值)它们都是预期值(2、1和100)。是什么导致了这种差异?

    0 回复  |  直到 5 年前