问题
I'm still trying to wrap my head around php, so sorry if this is a simple mistake (I've been searching for quite a while and can only manage to get different errors such as "undefined index")
What I'm attempting to do is have a function that will get data from a table (it doesn't contain a great deal at the moment, but will eventually contain everything for each main webpage). It should take an id then give the correct template and content for that page (just hard coding the $pageName in for now until I get it working)
in my Page class I have this
class Page{
public $pageid = null;
public $pagetemplate = null;
public $pagetitle = null;
public $pagebody = null;
public function __construct($data=array()){
if(isset($data['page_id'])) $this->pageid = (int) $data['page_id'];
if(isset($data['page_template'])) $this->pagetemplate = (string) $data['page_template'];
if(isset($data['page_title'])) $this->pagetitle = (string) $data['page_title'];
if(isset($data['page_body'])) $this->pagebody = (string) $data['page_body'];
}
public static function getPageData($pageName){
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$sql = "SELECT page_template, page_title, page_body FROM pages WHERE page_id = :page_id LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':page_id', $pageName);
$stmt->execute();
$list = array();
while($row = $stmt->fetch()){
//$pageslug = $row['page_slug'];
$page = new Page($row);
$list[] = $page;
}
$conn = null;
return(array("results" => $list));
}
}
then in my index I have
function homepage(){
$results = array();
$data = Page::getPageData(1);
$results['pages'] = $data['results'];
$template = $results['pages']->pagetemplate;
require($template);
}
The homepage function is called with a switch case but I'll change that later on so that the navbar changes the value given to getPageData and that should be how different pages are loaded. Anyway, I'm getting the following errors:
Notice: Trying to get property of non-object in C:\xampp\htdocs\index.php on line 48
Warning: require(): Filename cannot be empty in C:\xampp\htdocs\index.php on line 49
Fatal error: require(): Failed opening required '' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\index.php on line 49
回答1:
Your getPageData()
method returns a numerically indexed array at the 'results' index, not an object. This means $results['pages'] contains a numerically indexed array, not an object. var_dump()
it and check it out.
You likely need to do something like:
$template = $results['pages'][0]->pagetemplate;
回答2:
Change your function to return array(Page)
instead of array(array(Page))
$list = null;
while($row = $stmt->fetch()){
$page = new Page($row);
$list = $page;
}
Also, add additional check for result of query to return
来源:https://stackoverflow.com/questions/27098372/php-pdo-mysql-notice-trying-to-get-property-of-non-object