拜托朋友,我的代码需要帮助。
我的searchParent
函数多次执行self::
时总是返回NULL
class Search {
public function listParents() {
$sql = "SELECT id FROM parents";
return pg_query($sql);
}
public function searchParent($id) {
$parents= $this->listParents($con);
while ($r = pg_fetch_array($parent)){
if ($id === $r['id_parent']){
return $id;
}
}
$sql = "SELECT id_parent FROM parent WHERE id_parent = $id";
$query = pg_query($sql);
$result = pg_fetch_array($query);
self::searchParent($result['id_parent']);
}
}
我的电话,假设父表中有数字230
$id = $search->searchParent(230);
答案 0 :(得分:3)
您需要弄虚函数的 return 值。
在调用self::searchParent
之前,您应该添加return语句:
return self::searchParent($result['id_parent']);
答案 1 :(得分:0)
您可以使用count
和left join
来优化代码:
class Search
{
public function searchParent($id) {
$sql = "SELECT count(*) as cnt
FROM
parents LEFT JOIN parent on parent.id_parent = parents.id
WHERE
parents.id = $id";
$query = pg_query($sql);
$result = pg_fetch_array($query);
return empty($result['cnt']) ? null : $id;
}
}