当表字段名称与类变量名称相同时,将来自MySQL select的变量存储到PHP类变量的效率更高? [英] Store variables from MySQL select to PHP class variables more efficiently when the table field names are identical to the class variable names?
本文介绍了当表字段名称与类变量名称相同时,将来自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;
}
推荐答案
我建议采用这种方法:
$nameMap = array(
'id',
'companyId',
'url',
'name',
'contentType',
'fileSize',
'saved',
'retrieved',
);
foreach( $nameMap as $attributeName ) {
$this->$attributeName = $results->$attributeName ;
}
虽然可以写
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.
使用$nameMap
,该应用程序仍然可以正常工作.
Using $nameMap
, the application still works.
这篇关于当表字段名称与类变量名称相同时,将来自MySQL select的变量存储到PHP类变量的效率更高?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文