I'm really new to PHP and mySql, but I'm trying to figure out how to fetch all items from a table. In my item handler class I'm doing
static function getAllItems(){
$items = array();
$db = new Database();
$result = $db->query("SELECT * FROM items");
while($row = $result->fetch_assoc()){
$items[] = $row;
}
return $items;
}
and then on the client side I'm doing this to iterate through the items returned and display them, but keep getting an error
"Fatal error: Call to a member function getTitle() on a non-object"
What am I doing wrong?
<div class="table-responsive">
<?php
$allItems = ItemHandler::getAllItems();
if(empty($allItems)){
echo '<p class="lead text-center">No listings in this category yet.</p>';
} else {
echo '<table class="table">
<tr>
<th>Image</th>
<th>Item Name</th>
<th>Quantity</th>
<th>Description</th>
<th>Seller</th>
<th>Price</th>
<th>Purchase</th>
</tr>';
foreach($allItems as $item){
echo "<tr>
<td>blank</td>
<td>{$item->getTitle()}</td>
<td>1</td>
<td>{$item->getDescription()}</td>
<td>test seller</td>
<td>{$item->getPrice()}</td>
<td><a href='#'><button type='button' class='btn btn-primary'>Buy</button></a></td>
</tr>";
}
echo '</table>';
}
?>
</div>
I don't believe the problem is with any functions from my Item class. I believe it's how I'm creating the items with get all Items. Here's the code anyway. Items is included in my client side file.
class Item {
private $id;
private $title;
private $description;
private $imgPath;
private $category;
private $keywords;
private $postedTimestamp;
private $updatedTimestamp;
private $price;
private $published;
function __construct($id, $title, $description, $imgPath, $category, $keywords, $postedTS, $updatedTS, $price, $published){
$this->setId($id);
$this->setTitle($title);
$this->setDescription($description);
$this->setImgPath($imgPath);
$this->setCategory($category);
$this->setKeywords($keywords);
$this->setPostedTimestamp($postedTS);
$this->setUpdatedTimestamp($updatedTS);
$this->setPrice($price);
$this->setPublished($published);
}
public function getTitle()
{
return $this->title;
}
public function setTitle($title)
{
$this->title = $title;
return $this;
}
//other getters/setters of same format
When I do vardumpvar_dump($allItems[0]); this is returned, which is correct...
array (size=9) 'id' => string '1' (length=1) 'title' => string 'Test item' (length=9) 'description' => string 'test description' (length=16) 'imgPath' => string 'images/f141705f42bc438e1fa13ce21a04b67cc4568996-test1.gif' (length=57) 'price' => string '45' (length=2) 'postedTS' => string '2014-03-19 01:13:34' (length=19) 'updatedTS' => string '2014-04-16 21:39:19' (length=19) 'published' => string '1' (length=1)
'category' => string '1' (length=1)
var_dump($items[0]).