繁体   English   中英

PHP mySql从表中获取所有项目

[英]PHP mySql fetch all items from table

我是PHP和mySql的新手,但我正在试图弄清楚如何从表中获取所有项目。 在我的项目处理程序类中,我正在做

static function getAllItems(){

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

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

        while($row = $result->fetch_assoc()){
            $items[] = $row;
        }

        return $items;
}

然后在客户端我这样做是为了遍历返回的项目并显示它们,但不断收到错误

“致命错误:在非对象上调用成员函数getTitle()”

我究竟做错了什么?

<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>

我不相信我的Item类中的任何函数都存在问题。 我相信这是我用get all items创建项目的方式。 无论如何,这是代码。 项目包含在我的客户端文件中。

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

当我做vardumpvar_dump($allItems[0]); 这是返回的,这是正确的......

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'(长度= 19)'updatedTS'=>字符串'2014-04-16 21:39:19'(长度= 19)'已发布'=>字符串'1'(长度= 1)
'category'=>字符串'1'(长度= 1)

根据你的var_dump结果给出如下:

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'(长度= 19)'updatedTS'=>字符串'2014-04-16 21:39:19'(长度= 19)'已发布'=>字符串'1'(长度= 1)'类别'=>字符串'1'(长度= 1)

每个$item都是一个关联数组,每个项目中都有title和其他字段,因此可以使用以下方法访问它:

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

等等。

使用$item['title']而不是$item->getTitle().

请尝试修改代码。

<?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);
?> 

请根据需要更改您的代码。 我希望你能100%解决

尝试创建一个包含表模型的类,然后初始化setter和getter,之后你可以使用fnctions即

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

您需要创建所需对象的实例。 (项目)

您的代码当前将所有获取的行推送到数组中。

您需要处理这些行。

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;
}

我建议在PHP中使用PDO( http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ),因为它可以为你做所有这些'注入'(如果你想为多个数据库构建应用程序,那就更好) :

$yourstatement->fetchObject("Item")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM