Hi, I am attempting to do this project in PHP OOP utilizing abstract classes, getters, setters, however I am stuck at read function in an failed attempt to display the data into a html table. I am getting this error “Call to a member function prepare() on null”…
I will post the code here…
The product.class
abstract class Product
{
protected $conn;
protected $database;
protected $table;
protected $primaryKeys = [];
protected $attributes = [];
private $data = [];
protected function getDatabase() {
return $this->database;
}
protected function getTable() {
return $this->table;
}
protected function getFullTableName()
{
return '`' . $this->getDatabase() . '.' . $this->getTable() . '`';
}
protected function getPrimaryKeys() {
return $this->primaryKeys;
}
protected function setAttributes(array $attributes) {
$this->attributes = $attributes;
}
public function getAttributes() {
return array_merge($this->primaryKeys, $this->attributes);
}
public function setDatabaseConnection($conn) {
$this->conn = $conn;
}
protected function getDatabaseConnection() {
if (!$this->conn) {
throw new \Exception('Database Connection Uninitialized');
}
return $this->getDatabaseConnection;
}
}
This is a post.class with the read function…
class Post extends Product {
protected $conn;
protected $database = 'test';
protected $table = 'some';
protected $primaryKeys = ['id', 'sku', 'name'];
protected $attributes = ['price',
'productType', 'size', 'weight', 'height', 'length', 'width'];
public function read()
{
$db = $this->conn;
$query = "SELECT * FROM " . $this->getFullTableName();
$stmt = $db->prepare($query);
$stmt->execute();
$data = [];
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)){
$product = new Post();
$product->setAttributes($row['sku']);
$data[] = $product;
}
return $data;
}
This is the display attempt in the index.php file…
$products = new Post();
foreach ($products->read() as $product){
echo "<table>";
echo "<tbody>";
echo "<tr class='content'>";
echo "<th> <input type='checkbox' name='checkbox[]'> </th>";
echo "<td style='visibility: hidden'></td>";
echo "<td>" . implode(',', $product->getAttributes())."</td>";
echo "</tr>";
echo "</tbody>";
echo "</table>";
}
?>