我在这里有这部分代码(我当然有一个构造函数等,并创建了对象)
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出了什么问题。有什么帮助吗?
答案 0 :(得分: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']
答案 1 :(得分:0)
$results = array();
foreach($searchUserResult as $row){
$row['userBaseData'] = ??????;
$results[] = $row;
}
return $results;
更换??????用正确的变量。当前var名称错误!
现在至少你会返回空数组..
答案 2 :(得分: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;
尝试该代码。