0

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)

7
  • where's the ` getTitle()` function? Commented Apr 26, 2014 at 6:50
  • @Rorschach that's just a basic getter function in my Item class. Commented Apr 26, 2014 at 6:51
  • 1
    the problem is with getTitle which isn't shown in your code... please show all relevant code Commented Apr 26, 2014 at 6:51
  • Make sure it's not an associative array by var_dump($items[0]). Commented Apr 26, 2014 at 6:53
  • @WereWolf-TheAlpha I included the var_dump response in edit at bottom. Commented Apr 26, 2014 at 7:01

5 Answers 5

1

Use $item['title'] instead of $item->getTitle().

Sign up to request clarification or add additional context in comments.

1 Comment

yep this was it, as explained in answer below. can't use getters for it. thanks
1

According to your var_dump result given below:

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)

Each $item is an associative array and you have title and other fields in each item so access it using:

$item['title'];
$item['description'];

And so on.

Comments

0

Please try like your modify codes.

<?php
$con = mysql_connect("localhost", "root", "mypass") or
die("Could not connect: " . mysql_error());
mysql_select_db("tutorials");
$result = mysql_query("select * from tutorials");
echo "<table border='1' style='border-collapse: collapse'>";
echo "<th>Name of theTutorial</th><th>Pages</th><th>Examples</th><th>Author</th>";
while ($row = mysql_fetch_array($result)) 
{
echo"<tr><td>".$row['name']."</td><td>".$row['no_of_pages']."</td><td>".$row['no_of_examples']."</td><td>".$row['author']."</td></tr>";<br>}<br>echo "</table>";<br>mysql_close($con);
?> 

Please change your code dependable for your need. I expect you will get solve 100%

Comments

0

Try to create a class contains the model of the table, then initialise the setter and getter, after that you can use the fnctions i.e

class model{
private $title;
private $description;
private $price;
//...
public function getTitle(){
return $title;
}
//..
}

Comments

0

You need to create an instance of the required object. (Item)

Your code currently pushes all fetched rows into an array.

You need to process those rows.

static function getAllItems(){

    $items = array();
    $db = new Database();

    $result = $db->query("SELECT * FROM items");

    while($row = $result->fetch_assoc()){
        $items[] = new Item($row["id"], $row["title"], $row["description"], $row["imgPath"], $row["category"], $row["keywords"], $row["postedTS"], $row["updatedTS"], $row["price"], $row["published"]);
    }

    return $items;
}

I'm recommending using PDO with PHP (http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers), because it can do all these 'injections' (and much better if you want to build your application for multiple databases) for you like this:

$yourstatement->fetchObject("Item")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.