简体   繁体   English

使用PDO查询嵌套在while循环中的Foreach

[英]Foreach nested in a while loop with PDO query

To trim the fat so-to-speak in my script I decided to use 1 PDO prepare to span an array of predefined tables. 为了减少我的脚本中要说的繁琐代码,我决定使用1个PDO准备覆盖一组预定义表。 The PDO executes in a while loop and within the while loop there is a foreach to build the output of each result set. PDO在while循环中执行, while while循环中有一个foreach来构建每个结果集的输出。

This is code for a search. 这是搜索代码。 The script currently searches 3 tables for results (through the while iterations). 该脚本当前在3个表中搜索结果(通过while迭代)。 We will call them tables a, b, and c. 我们将它们称为表a,b和c。 For the tested search it finds 2 results in table a, 0 in table b, and 1 in table c. 对于经过测试的搜索,它在表a中找到2个结果,在表b中找到0个结果,在表c中找到1个结果。

Though it finds a total of 3 results it only displays 2. One from table 'a' and one from table 'c'. 尽管它总共找到3个结果,但只显示2。一个来自表'a',一个来自表'c'。 The script is not building the result from the second find in the table 'a'. 该脚本未根据表“ a”中第二个查找结果生成结果。

I have looked it over until my eyes bleed and searched for maybe something I have wrong, I cant figure it out. 我一直看着它,直到我的眼睛流血并寻找可能是我做错的事情,我无法弄清楚。 Any ideas of what is wrong with this code? 关于此代码有什么问题的任何想法?

// --- Build an array of places to search
$tableArray = array("services", "webPages", "dsiu");
$tableCount = count($tableArray);
$count = "0";
$resCount = "0";

$result = "";
while ($tableCount > $count) {
    // -- Search tables in the array for matches
    $quotedString = $db->quote($searchString);
    $qSQL = "SELECT title, ldesc, SUM(MATCH(title, sdesc, ldesc) AGAINST(:string IN BOOLEAN MODE)) AS score FROM ".$tableArray[$count]." WHERE MATCH (title, sdesc, ldesc) AGAINST (:string IN BOOLEAN MODE) ORDER BY score DESC";
    $q = $db->prepare($qSQL);
    $q->execute(array(':string'=>$quotedString));

    // -- keep a count of the results
    $rowCount = $q->rowCount();

    if ($rowCount > 0) {
        $resCount = $resCount + $rowCount;

        // -- build result html
        $html = $q->fetchAll(PDO::FETCH_ASSOC);
        foreach ($html as $row) {

            // --- Clean the results for display
            $desc = cleanURL($row['ldesc']);
            $desc = str_ireplace($searchString, '<b><font color="green">'.$searchString.'</font></b>', $desc);
            $desc = substr($desc, 0, 300)."...";

            $result .= "<font color='red'><b>".$row['title']."</b></font><br>".$desc."<br><br>";

        }
    }

    $count++;
}

Thanks @dan08. 谢谢@ dan08。 I added a if ($row['score'] != null) { to the foreach . 我添加了一个if ($row['score'] != null) {foreach Also discovered that SUM() in the query was removing what should have been results. 还发现查询中的SUM()正在删除应为结果的内容。

This is now working with the changes. 现在正在处理这些更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM