PHP返回空数组,MySQL返回集合
直接在phpMyAdmin中运行SQL代码与使用PHP的PDO之间存在差异。这是我的PHP代码:PHP返回空数组,MySQL返回集合,php,mysql,pdo,Php,Mysql,Pdo,直接在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['use
<?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);
?>
它打印一个空数组。但是,如果我在phpMyAdmin中直接运行SQL,它将返回预期的集合。我甚至不知道如何调试它,因为如果我回显
$userId
、$limit
和$offset
(我在参数中传递的值),它们都是预期值(2、1和100)。是什么导致了这种差异?您可以在sql中输入错误,当您运行sql时,它将打印它正在执行的查询,您可以在phpmyadmin上尝试相同的查询。谢谢@danish-khan-I问题是,尽管我将参数指定为PARAM_INT,但出于某种原因,它将其转换为字符串。解决方案是对变量调用intval()。@David或者您可以强制转换为int
,即(int)$limit
{
"userId": 2,
"current": 1,
"rowCount": 100
}