PDO fetchAll 和 foreach 不返回第一行

PDO fetchAll and foreach not returning first row

我的 PHP 里有这个:

$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$selected_client = $_POST['client'];
$sql = 'SELECT `cohort_id`,`cohort_name`, `cohort_description` FROM table_cohorts where client_id = :client';
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY) );
$stmt->execute(array(':client' => $selected_client));
foreach ($stmt as $row){
$result = $stmt->fetchAll();
}
header('Content-type: application/json');
echo json_encode($result);

这 returns 几乎是正确的。它 returns 我的数据库 table 中所有相关的预期行,除了第一行。我猜我正在以某种方式覆盖它,但不确定哪里出错了。

不确定为什么你有一个 foreach 循环。当您想要的是所有行时,您将在 $result 上使用 foreach 循环遍历行,因此您将放弃循环。

foreach ($stmt as $row){
    $result = $stmt->fetchAll();
}

只保留这部分。

$result = $stmt->fetchAll();

只需使用

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

并摆脱 foreach 循环。