[英]PHP MySQL query not returning all results
我在PHP中执行以下SQL查询无法完全正常工作。 结果仅包含第一行。 该查询在PHPMyadmin中完全可以正常工作,它向我返回所有结果。
$select = "SELECT a.setID, a.setName, a.setPrimaryLanguage, a.setSecondaryLanguage
FROM Person_Set ps, Album a
WHERE ps.Person_username = :username
AND ps.Set_setID = a.setID";
try {
$stmt = $dbh->prepare($select, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$stmt->bindValue(":username", $username, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch();
echo json_encode($result);
unset($stmt);
} catch (Exception $e) {
echo 'Exception : ' . $e->getMessage() . "\n";
}
此外,如果我更改选择标准以搜索包含某些字符串的行,则结果为空(返回“ false”)。 查询如下:
$select = "SELECT a.setID, a.setName, a.setPrimaryLanguage, a.setSecondaryLanguage
FROM Album a, Set_Card s
WHERE a.setName LIKE '%:searchText%'
AND a.setID = s.Set_setID
GROUP BY a.setID";
我一直在尝试不同的方法来连接到MySQL并获取结果,例如
$results = $mysqli->query($query);
而不是使用PDO。 但是,结果仍然相同。 谁能指出我的错误在哪里? 非常感谢你!
PDOStatement :: fetch —从结果集中获取下一行
因此,当您仅执行获取操作时,它会获取第一行,除非您使用将光标更改为下一条记录的循环来执行此操作。
您可以使用fetchAll
方法获取所有记录
PDOStatement :: fetch提取一行并将指针移至下一行。 您将使用$results = $stmt->fetchAll()
检索所有结果,或者使用如下所示的循环:
while ($result = $stmt->fetch()) {
echo json_encode($result);
}
嗨,您正在使用fetch()函数,该函数仅获取一行,而使用此代码,
$select = "SELECT a.setID, a.setName, a.setPrimaryLanguage, a.setSecondaryLanguage
FROM Person_Set ps, Album a
WHERE ps.Person_username = :username
AND ps.Set_setID = a.setID";
try {
$stmt = $dbh->prepare($select, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$stmt->bindValue(":username", $username, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchall();
echo json_encode($result);
unset($stmt);
} catch (Exception $e) {
echo 'Exception : ' . $e->getMessage() . "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.