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();

}

我找到的所有这些很棒的功能:

免责声明:此代码未经过测试:(

保持凉爽,但要保持温暖

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值