php 获取 table,php – 获取表对象(App_Model_TableName)作为获取结果(Zend Framework)
現在,我在我的模型中寫了一個函數:
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();
}
我找到的所有這些很棒的功能:
免責聲明:此代碼未經過測試:(
保持涼爽,但要保持溫暖
總結
以上是生活随笔為你收集整理的php 获取 table,php – 获取表对象(App_Model_TableName)作为获取结果(Zend Framework)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux清除cpu,解决kswapd0
- 下一篇: 简单的ajax上传商品功能使用Sevle