pdo - Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\cms\include\article.php on line 8 -
i getting error , wondering how fix it? when trying add articles feed.
class article { public function fetch_all() { global $pdo; $query = $pdo->prepare("select * articles order `article_id` desc"); $query->execute(); return $query->fetchall(); } public function fetch_data($article_id) { global $pdo; $query = $pdo->prepare("select * articles article_id = ?"); $query->bindvalue(1, $article_id); $query->execute(); return $query->fetch(); } } ?>
don't use global
attempt. that's not oop design , 1 of reasons whey code fails. instead make sure have been created $pdo
far , pass constructor of article
.
further note capability of called typehints
. while using them can enforce special type method param. if pass value @ runtime (like null or else) php throw error:
typehint-----------------| public function __construct(pdo $pdo) { $this->pdo = $pdo; }
example:
class article { protected $pdo; // type hint makes !!sure!! pdo connected public function __construct(pdo $pdo) { $this->pdo = $pdo; } public function fetch_all() { $query = $this->pdo->prepare("select * articles order `article_id` desc"); $query->execute(); return $query->fetchall(); } public function fetch_data($article_id) { // note this: $query = $this->pdo->prepare("select * articles article_id = ?"); $query->bindvalue(1, $article_id); $query->execute(); return $query->fetch(); } }
call this:
$pdo = new pdo($connectionstring, $user, $pass); $article = new article($pdo); var_dump($article->fetch_data($someid));
Comments
Post a Comment