我设法编辑我从教程中复制的代码
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,我的问题是如果我希望颜色显示而不是全部。
答案 0 :(得分: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;
}
答案 1 :(得分:0)
在代码中更改这两行
$sql = "SELECT `colour` FROM dbo.guitar WHERE id=:id";
和
array('colour')
答案 2 :(得分: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')
会提取id
,make
和model
。
这个解决方案可能有点粗糙,因此可以做更多的工作,但这应该可以帮助你。