mysql select变量做字段名,当表字段名称与类变量名称相同时,将MySQL select中的变量存储到PHP类变量中的效率更高?...

I am selecting data from a database. The database field names are exactly the same as the class variable names. Is there a way to store this data into the class variables without specifying each one individually?

//gets info about a specified file.

//chosen based on a supplied $fileId

function getFileInfo($fileId)

{

//select info from database

$sql = "SELECT id, companyId, url, name, contentType, fileSize, saved, retrieved

FROM files

WHERE id = $fileId";

$results = $this->mysqli->query($sql);

$results = $results->fetch_object();

//store info into class variables

$this->id = $results->id;

$this->companyId = $results->companyId;

$this->url = $results->url;

$this->name = $results->name;

$this->contentType = $results->contentType;

$this->fileSize = $results->fileSize;

$this->saved = $results->saved;

$this->retrieved = $results->retrieved;

}

解决方案

I'd propose this approach:

$nameMap = array(

'id',

'companyId',

'url',

'name',

'contentType',

'fileSize',

'saved',

'retrieved',

);

foreach( $nameMap as $attributeName ) {

$this->$attributeName = $results->$attributeName ;

}

While one could write

foreach($result as $var => $value) {

...

}

the outcome fully depends on backing table's structure. If you add further attributes to the table, your code might break.

Using $nameMap, the application still works.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值