0

我在这里有这部分代码(我当然有一个构造函数等并创建了对象)

function searchUsers($term)
{
    $searchUserSQL = "SELECT userID, givenName, familyName from userbase where givenName or familyName = :name";
    $searchUserPrepare = $this->prepare($searchUserSQL);
    $searchUserPrepare->bindParam(':name', $term);
    $searchUserPrepare->setFetchMode(PDO::FETCH_ASSOC);
    $searchUserPrepare->execute();
    $searchUserResult = $searchUserPrepare->fetchAll();
    foreach($searchUserResult as $row){
            $row['userBaseData']=$this['givenName'];
            $results[] = $row;
        }
        return $results;
}

但结果始终为 NULL。当我在 PHPmyAdmin 中测试这个 qry 时,我也没有得到任何结果。

但是在我的表userbase中有一个名为userID、givenName和familyName的列名,而且搜索词也是正确的。我不知道我的 qry 做错了什么。有什么帮助吗?

4

3 回答 3

2

SELECT userID, givenName, familyName from userbase where givenName or familyName = :name

我什至不确定该查询将如何工作,特别是在 WHERE 子句中。

SELECT
    u.userID
  , u.givenName
  , u.familyName
FROM `userbase` u
WHERE u.givenName = :given_name
  OR u.familyName = :family_name;

然后绑定$term到两者:given_name:family_name


编辑整个事情在一起(重写)

function searchUsers( $term )
{
    $sql = <<<SQL
SELECT
    u.userID
  , u.givenName
  , u.givenName AS `userBaseData`
  , u.familyName
FROM `userbase` u
WHERE u.givenName = :given_name
  OR u.familyName = :family_name;
SQL;

    $stmt = $this->prepare( $sql );
    $stmt->bindParam( ":given_name", $term, PDO::PARAM_STR );
    $stmt->bindParam( ":family_name", $term, PDO::PARAM_STR );
    $stmt->execute();

    return ( $stmt->rowCount() > 0 )
        ? $stmt->fetchAll( PDO::FETCH_ASSOC )
        : array();

}

编辑 2

真的不知道你想用$row['userBaseData'] = $this['givenName']

于 2013-03-25T15:55:13.683 回答
0

我假设您使用的是 PDO,那么您必须先连接到数据库:

$conector = new connection("server","database"); // Your custom class to connect to a DB
$con = $conector->connect(); // Return the connector
$con->exec('SET CHARACTER SET utf8'); // A must have
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // A must have to handle exceptions and know better the errors that it gives, use try - catch
$consulta = $con->prepare("SELECT userID, givenName, familyName from userbase where givenName or familyName = :name;");
$consulta->bindParam(':name', $name, PDO::PARAM_STR);
$data = array('name' => $term);
$consulta->execute($data);
foreach($consulta as $row){
        $row['userBaseData']=$this['givenName'];
        $results[] = $row;
}
return $results;

试试那个代码。

于 2013-03-25T16:05:05.517 回答
0
    $results = array();    
    foreach($searchUserResult as $row){
        $row['userBaseData'] = ??????;
        $results[] = $row;
    }
    return $results;

更换 ??????具有正确的变量。当前的变量名是错误的!

现在至少你会返回空数组..

于 2013-03-25T15:53:41.693 回答