Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

Fatal error: Uncaught Error: Call to a member function prepare() on null

User.php <?php

class User {
	private $db;

	public function __construct() {
		$this->db = new PDO('mysql:host=localhost;dbname=php', 'root', '');
	}

	public function getAll() {
		$stmt = $this->db->query('SELECT * FROM users');
		return $stmt->fetchAll(PDO::FETCH_ASSOC);
	}

	public function create($name, $email) {
		$stmt = $this->db->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
		$stmt->execute(['name' => $name, 'email' => $email]);
	}

	public function getById($id) {
		$stmt = $this->pdo->prepare('SELECT * FROM users WHERE id = :id');
		$stmt->execute(['id' => $id]);
		return $stmt->fetch(PDO::FETCH_ASSOC);
	}
}

I see this error

Warning: Undefined property: User::$pdo in C:\xampp\htdocs\mvc\User.php on line 21 Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\mvc\User.php:21 Stack trace: #0 C:\xampp\htdocs\mvc\UserController.php(30): User->getById('1') #1 C:\xampp\htdocs\mvc\route.php(12): UserController->edit('1') #2 C:\xampp\htdocs\mvc\index.php(2): require_once('C:\xampp\htdocs...') #3 {main} thrown in C:\xampp\htdocs\mvc\User.php on line 21

0 likes
2 replies
Snapey's avatar

Do you see anywhere where you initialise $this->pdo ?

Start with the basics buddy. Do some learning

shahr's avatar
Level 10

I can solve it.

<?php

class User {
	private $db;

	public function __construct() {
		$this->db = new PDO('mysql:host=localhost;dbname=php', 'root', '');
	}

	public function getAll() {
		$stmt = $this->db->query('SELECT * FROM users');
		return $stmt->fetchAll(PDO::FETCH_ASSOC);
	}

	public function create($name, $email) {
		$stmt = $this->db->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
		$stmt->execute(['name' => $name, 'email' => $email]);
	}

	public function getById($id) {
		$stmt = $this->db->prepare('SELECT * FROM users WHERE id = :id');
		$stmt->execute(['id' => $id]);
		return $stmt->fetch(PDO::FETCH_ASSOC);
	}
}

Please or to participate in this conversation.