现在,我在我的模型中写了一个函数:
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
免责声明:此代码未经过测试:(
保持凉爽,但要保持温暖