0

以下代码返回给我类似电话号码的人。它工作得很好,但是当没有数字时,该函数仍然返回信息,这意味着如果没有其他人具有相似数字,我无法选中隐藏某个框。

功能

function getothers($tid,$criteria,$telephone,$telephone2,$elector){
            global $dbh;
            $tid = '-TID'.$tid;
             $sql = "SELECT * FROM electors WHERE ((telephone > 0 AND telephone IN ('$telephone','$telephone2'))  OR (telephone2 > 0 AND telephone2 IN ('$telephone','$telephone2'))) $criteria AND records NOT RLIKE '$tid' AND ID != '$elector'  LIMIT 10";
            $result = $dbh->query($sql);
            return $result;
        }

召唤

<?php $others = getothers($post['TID'],$post['criteria'],$elector['telephone'],$elector['telephone2'],$elector['ID']); ?>

行不通的线路

<?php if(!$others){?> 

$others尽管没有结果,但仍然有一些东西。我想我可能在 y PDO 中遗漏了一行。有任何想法吗?

print_r

PDOStatement Object ( [queryString] => SELECT * FROM electors WHERE ((telephone > 0 AND telephone IN ('02085414023 ','')) OR (telephone2 > 0 AND telephone2 IN ('02085414023 ',''))) AND (this_vi_street = '' AND this_vi_telephone = '') AND (mosaic IN ('A01','A02','A03','A04','A05','A07','B11','C15','C16','C17','C18','H46','J52','K57','K58','K60') OR last_vi IN ('C','P')) AND postal_vote != 1 AND records NOT RLIKE '-TID1' AND ID != '13' LIMIT 10 )
4

2 回答 2

1

根据评论,使用准备好的语句的版本:

function getothers($tid, $criteria, $telephone, $telephone2, $elector) {
    global $dbh;

    $stmt = $dbh->prepare("SELECT *
                             FROM electors
                            WHERE ((telephone > 0 AND telephone IN (:telephone, :telephone2))
                                   OR (telephone2 > 0 AND telephone2 IN (:telephone, :telephone2)))
                                  $criteria
                                  AND records NOT RLIKE :tid
                                  AND ID != :elector
                            LIMIT 10";

    $stmt->execute(array(
        ':telephone'  => $telephone,
        ':telephone2' => $telephone2,
        ':tid'        => '-TID' . $tid,
        ':elector'    => $elector
    ));

    return $stmt->fetchAll();
}

这段代码还是有一些不好的地方:

  • 用于global获取数据库连接,这是整体糟糕的应用程序结构。您可能应该使用一个类或$dbh作为常规参数传递给函数。
  • 连接$criteria到准备好的语句中。您真的需要这样的动态条件,以至于如果不将整个 SQL 块连接到其中就无法为其准备查询?
  • 不一定解决您的函数返回的实际问题。
于 2012-07-02T13:31:54.473 回答
0

也许做类似的事情

$result = $dbh->query($sql);
if($result->rowCount()>0)
{
return $result;
}

return false;
于 2012-07-02T13:02:36.287 回答