PHP Error:Fatal error: Call to a member function fetch_assoc() on a non-object in

Unfortunately, I am still getting the same error after updating my code to prepared statements. It seems to rarely occur when a user or bot tries to reach some invalid URL. Below is my function:

function get_post($category_name, $post_name) {
	$category_name = preg_replace('/[^a-z0-9-]/', '', $category_name);
	$post_name = preg_replace('/[^a-z0-9-]/', '', $post_name);
	$stmt = DB::$db->prepare("SELECT * FROM posts LEFT JOIN categories ON category_id = post_category WHERE category_name = ? AND post_name = ?");
	$stmt->bind_param('ss', $category_name, $post_name);
	$stmt->execute();
	$result = $stmt->get_result();
	$post = $result->fetch_assoc();
	if (empty($post)) {
		require('404.php');
		exit;
	}
	return $post;
}

The error is:

PHP Fatal error: Call to a member function fetch_assoc() on a non-object

it points to this line:

$post = $r->fetch_assoc();

How can I modify the function so that it will not give a fatal error, instead it will check if the fetch_assoc() is successful and display 404 if it is not?

Thanks.