未找到结果时显示消息POSTGRESQL PHP

时间:2018-03-23 18:48:28

标签: php postgresql

我有一个PHP脚本连接到POSTGRESQL数据库并使用全文搜索。

问题:

如果关键字匹配,我会得到我的结果,但如果没有匹配,我就不会得到任何结果。但不是抛出“没有找到记录”的陈述,而是空白。

SQL声明:

<?php 
$words = $_POST["search"];
$sql =<<<EOF
     SELECT pid, p_code, p_category, p_title, p_description, mf_cat, p_thumb
FROM (SELECT tblproducts.product_id as pid,
             tblproducts.product_code AS p_code,
             tblproducts.product_category AS p_category,
             tblproducts.product_title as p_title,
             tblproducts.product_description AS p_description,
             tblproducts.product_mf_catalog AS mf_cat,
             tblproducts.product_thumb AS p_thumb,
             setweight(to_tsvector(COALESCE(tblproducts.product_title)), 'A') || 
             setweight(to_tsvector(COALESCE(tblproducts.product_description)), 'C') ||
             setweight(to_tsvector(COALESCE(tblproducts.product_category)), 'B') ||
             setweight(to_tsvector(COALESCE(tblproducts.product_code)), 'D') AS DOCUMENT
      FROM tblproducts
      GROUP BY tblproducts.product_id) p_search
WHERE mf_cat = '1' AND p_search.document @@ to_tsquery('english', replace('$words:*', ' ', '&'))
ORDER BY ts_rank(p_search.document, to_tsquery('english', replace('$words:*', ' ', '&'))) DESC;
EOF;

$ret = pg_query($dbc, $sql)
or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");
?>

显示结果

<?php 
if ($ret) {                        
    while ($row = pg_fetch_row($ret)) {

echo "
    <div class='col-6 col-md-3 mb-4'>
      <div class='card-invis h-100'>
      <div class='card-body'>
        <a href='product-details.php?pid=$row[0]'><img class='card-img-top img-responsive' src='https://marque-foods.azureedge.net/website-files/$row[6]' alt='$row[3]'></a>
        <p class='my-1 card-text text-red text-left'>$row[3]</p>
        <p class='card-text text-gray text-left'>$row[1]</p>
      </div>
    </div>  
  </div>";
    }
pg_close($dbc);
} 

else {
echo 'no results found';
}
?>

1 个答案:

答案 0 :(得分:0)

使用pg_num_rows,返回“结果中的行数”:

if (pg_num_rows($ret)) {
    while ($row = pg_fetch_row($ret)) { /* your code here */ }
} else {
    echo 'Nothing found.';
}