Home  >  Article  >  Backend Development  >  ThinkPHP中数据操作案例分析_php实例

ThinkPHP中数据操作案例分析_php实例

WBOY
WBOYOriginal
2016-06-07 17:11:23895browse

本文实例分析了ThinkPHP中数据操作方法。分享给大家供大家参考。具体如下:

模板中使用函数,相信大部分的TPer都知道也用过吧。

案例:

获取用户名的方法

function get_username($uid){
  $row = M('User')->getbyUid($uid);
  return $row['username'];
}

在模板中通过uid显示用户名

<volist name="rows" id="row">
<tr>
  <td>{$row.uid}</td>
  <td>{$row.uid|get_username}</td>
</tr>
</volist>

这种方法相信大伙应该很常用吧?这种用法有两个不好的地方:

1、过多数据库操作;
2、数据操作的位置不合理,数据库连接过长。

优化方案:

1、尽可能把能合并的数据库操作;
2、数据操作应该保留在数据层,尽可能避免在视图里操作数据库,建议在视图开始前执行mysql_close(),断开数据库连接。

希望本文所述对大家基于ThinkPHP的php程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn