[英]PHP PDO Row Counting
我想檢查是否有任何事件使用host_id參數綁定到主機的行,如果沒有任何事件綁定到主機,則不會打印任何內容,但是如果主機綁定到其中一個事件,則一切正常,它沒有列出事件,但是如果我刪除下面指出的代碼並在此處注釋問題,而問題在此處結束,它將列出事件。 我也在上面的fetchAll函數中使用另一件事,上面沒有這樣的錯誤,但是在下面的部分中,它沒有列出事件,我該如何解決?
謝謝
try
{
$eq = "SELECT * FROM `events` WHERE `host_id` = :id AND `confirmed` = '1' ";
$eq_check = $db->prepare($eq);
$eq_check->bindParam(':id', $id, PDO::PARAM_INT);
$eq_check->execute();
//problem starts here
$count3 = $eq_check->fetchAll();
$rowCount = count($count3);
if ($rowCount == 0)
{
echo "None";
}
//problem ends here
while($fetch = $eq_check->fetch (PDO::FETCH_ASSOC) )
{
$_loader = true;
$event_id = $fetch['event_id'];
$event_name = $fetch['event_name'];
$link = "https://www.mywebsite.com/e/$event_id";
echo "<a target=\"_blank\" href=\"$link\"><li>$event_name</li></a>";
}
}
catch(PDOException $e)
{
$log->logError($e." - ".basename(__FILE__));
}
謝謝
您也無法執行兩次就無法獲取兩次。 如果您不只是想重復使用$count3
項,還可以觸發closeCursor()
然后再觸發execute()
再次獲取該集合。
要重用$count3
變量,請將while
循環更改為: foreach($count3 as $fetch) {
它沒有列出您的代碼時列出的事件的原因是,已經使用fetchAll語句來獲取結果集( fetchAll
不會留下任何內容,以后再通過fetch
)。
在這種情況下,最好運行select count(*)
以獲取行數,然后實際運行完整查詢以遍歷結果:
PDO中的一個示例在這里 :
<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
請注意,您不能直接使用rowCount來獲取所選行的計數-而是顯示已刪除的行數等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.