现在,我在模型中编写了一个函数:
public function getRowsByZipCode($zip)
{
// SQL to get all the rows with the given zip code
$stmt = $this -> getAdapter()
-> query( "SELECT *
FROM
table_name
WHERE
table_name.status = 1 AND
table_name.zip={$zip}");
$resultRows = $stmt->fetchAll();
// -------------------------------------------------------- //
// Convert result set to an array of objects
$resultObjects = array();
// If there is atleast one row found in DB
if(count($resultRows) > 0)
{
// Loop throguh all the rows in the resultset
foreach($resultRows as $resultRow) {
// Create table row and fill it with the details got from DB
$h = $this->createRow();
$h->setFromArray($resultRow);
// Add to the array
$resultObjects[] = $h;
}
}
return $resultObjects;
// -------------------------------------------------------- //
}
这完全符合我的需要。它向我返回了一个数组,其中包含表行对象(App_Model_TableName对象(、,这些对象稍后将用于保存和删除等进一步操作。
我真正想要的是删除循环通过我从结果集中得到的行的代码,并将每一行转换为我在注释//---//中写的App_Model_TableName的对象。
提前谢谢。
首先,我假设您正在使用PDO。
尝试以下
class App_Model_TableName
{
public $status;
public $zip;
// public $other_column;
}
class YourClass
{
protected function getAdapter()
{
// Do adapter stuffs
}
public function query($query, array $param)
{
// When Using PDO always use prepare and execute when you pass in a variable
// This will help prevent SQL injection
$stmt = $this->getAdapter()->prepare($query);
return $query->execute($param);
}
/**
* @return App_Model_TableName[]
*/
public function getRowsByZipCode($zip)
{
// SQL to get all the rows with the given zip code
// This way will help prevent SQL injection
$query = "SELECT * FROM table_name WHERE table_name.status = 1 AND table_name.zip = :zip";
$qData = array(':zip' => $zip);
$results = $this->query($query, $qData);
return $results->fetchAll(PDO::FETCH_CLASS, 'App_Model_TableName');
}
}
调用YourClass::getRowsByZipCode()
将返回一个App_Model_TableName
对象数组。然后您可以访问它们,如:
$data = $instance_of_yourclass->getRowsByZipCode(12345);
foreach ($data as $row)
{
echo $row->zip;
echo $row->do_stuff();
}
我在上发现了所有这些很棒的功能
- http://php.net/manual/en/pdostatement.fetchall.php
- http://php.net/manual/en/pdostatement.execute.php
免责声明:此代码未经测试:(
保持凉爽但保持温暖
最后,我找到了解决方案:
public function getRowsByZipCode($zip)
{
// SQL to get all the rows with the given zip code
$stmt = $this -> getAdapter()
-> query( "SELECT *
FROM
table_name
WHERE
table_name.status = 1 AND
table_name.zip={$zip}");
$resultObjects= array();
while($data = $stmt->fetch())
{
$h = $this->createRow();
$h->setFromArray($data);
// Add to array
$resultObjects[] = $h;;
}
return $resultObjects;
}
我已经删除了执行fetchAll((并循环遍历结果集中每一行的代码。现在,我从结果集中提取每一行,并使用从结果集中获得的数据创建一行App_Model_TableName对象。
非常适合我。