-3

我设法编辑了从教程中复制的代码

public function viewItem(){

    self::conn();
    try {
        $sql = "SELECT * FROM dbo.guitar WHERE id=:id";
        $q = self::$db->prepare($sql);
        $q->execute(array(':id' => $this->id));
        $row = $q->rowCount();
        if ($row == 0)
        {
            echo 'no records found.';
        }
        else
        {
            $results = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,
            "Guitar",
            array('id', 'make', 'model', 'colour', 'price'));
        }
    }catch (Exception $e){
        print "Error!: " . $e->getMessage();
    }
    return $results;    
}

根据Id,我获取了所有数据,我的问题是如果我希望颜色全部显示怎么办。

4

3 回答 3

1

这将只返回颜色:

public function viewItem(){

    self::conn();
    try {
        $retVal = array();
        $sql = "SELECT * FROM dbo.guitar WHERE id=:id";
        $q = self::$db->prepare($sql);
        $q->execute(array(':id' => $this->id));
        $row = $q->rowCount();
        if ($row == 0)
        {
            echo 'no records found.';
        }
        else
        {
            $results = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,"Guitar",

            foreach($result as $row)
                $retVal[] = $row['colour'];
        }
    }catch (Exception $e){
        print "Error!: " . $e->getMessage();
    }
    return $retVal;    
}
于 2012-10-09T06:48:09.983 回答
0

更改代码中的这两行

$sql = "SELECT `colour` FROM dbo.guitar WHERE id=:id";

array('colour')
于 2012-10-09T06:48:00.213 回答
0

答案比较简单:

public function viewItem(array $fields = array('id', 'make', 'model', 'colour', 'price'))
{
    self::conn();
    try {
        $sql = "SELECT ".implode(',',$fields)." FROM dbo.guitar WHERE id=:id";
        $q = self::$db->prepare($sql);
        $q->execute(array(':id' => $this->id));
        $row = $q->rowCount();
        if ($row == 0)
        {
            echo 'no records found.';
        }
        else
        {
            $results = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,
            "Guitar",$fields);
        }
    }catch (Exception $e){
        print "Error!: " . $e->getMessage();
    }
    return $results;    
}

此方法接受一个数组参数,或者根本不接受任何参数。通过array('colour'),您将只查询colour数据。不传递参数会获取所有数据,而array('id', 'make', 'model')fetches和.idmakemodel

这个解决方案可能有点粗糙,因此可以做更多的工作,但这应该可以帮助你。

于 2012-10-09T06:49:49.843 回答