用PHP中的函数获取数组值

时间:2022-08-19 09:51:56

What is the proper way to create a function to get array values from a query? I am getting "Undefined index: page_title" error. However I can get the value without function like: echo $row->page_title; Or echo $query[0]->title;

创建函数以从查询中获取数组值的正确方法是什么?我收到“Undefined index:page_title”错误。但是我可以获得没有函数的值,如:echo $ row-> page_title;或echo $ query [0] - > title;

function get_page($id) {

    $db = new DB();

    $query = $db->get_rows("SELECT * FROM pages WHERE id = :id ", array('id' => $_GET['id']) );

    foreach ($query as $row) {
        $page_id = $row->id;
        $page_title = $row->title;
    }

    return $query;

}

$page = get_page(1);

echo $page['page_title'];

here is my database class:

这是我的数据库类:

function get_rows($query, $values=array(), $fetchType = FETCH_OBJ)
{
    $sth = $this->dbh->prepare($query);
    if(is_array($values) && (sizeof($values) > 0))
    {
        foreach($values as $key=>$val)
        {
            $key = is_numeric($key) ? ($key + 1) : $key;
            $sth->bindValue($key,$val); 
        }
    }
    if($sth->execute())
        return $sth->fetchAll($fetchType);
}

1 个解决方案

#1


To make the function reusable, I would rewrite it the following way

为了使函数可重用,我将按以下方式重写它

function get_page($id, $col) {
  $db = new DB();

  $query = $db->prepare('SELECT * FROM pages WHERE id = :id');
  $query->execute(array(':id' => $id));
  $results = $query->fetch(PDO::FETCH_NUM);

  return $results[0][$col]; 
}

$page = get_page(1, 'page_title');
echo $page;

I skipped the foreach as you said that all id's are unique so you should only ever have 1 result

当你说所有id都是唯一的时候我跳过了foreach,所以你应该只有1个结果

Also it may not be a bad idea to add some error checking to make sure you do get back what you expect from the query and to make sure it is not empty.

此外,添加一些错误检查可能并不是一个坏主意,以确保您确实获得了对查询的期望,并确保它不为空。

Edit: Sorry if the syntax is a little off, dont have anything to test the code against quickly.

编辑:对不起,如果语法稍微偏离,没有任何东西可以快速测试代码。

#1


To make the function reusable, I would rewrite it the following way

为了使函数可重用,我将按以下方式重写它

function get_page($id, $col) {
  $db = new DB();

  $query = $db->prepare('SELECT * FROM pages WHERE id = :id');
  $query->execute(array(':id' => $id));
  $results = $query->fetch(PDO::FETCH_NUM);

  return $results[0][$col]; 
}

$page = get_page(1, 'page_title');
echo $page;

I skipped the foreach as you said that all id's are unique so you should only ever have 1 result

当你说所有id都是唯一的时候我跳过了foreach,所以你应该只有1个结果

Also it may not be a bad idea to add some error checking to make sure you do get back what you expect from the query and to make sure it is not empty.

此外,添加一些错误检查可能并不是一个坏主意,以确保您确实获得了对查询的期望,并确保它不为空。

Edit: Sorry if the syntax is a little off, dont have anything to test the code against quickly.

编辑:对不起,如果语法稍微偏离,没有任何东西可以快速测试代码。