PHP-Phalcon框架中的数据库操作

发表于:2016-5-05 10:28

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:露夕逝    来源:51Testing软件测试网采编

  4. 数据库操作
  在Phalcon中操作数据库提供了基本的ORM映射方式以及更加复杂的PHQL方式。ORM映射方式支持不写SQL语句直接操作数据库,基本上已经提供了绝大多数使用场景的支持;另一种更为高级的PHQL方式,支持编写Phalcon化的SQL语句来操作数据库。这里不编写SQL语句,直接使用ORM映射本身提供的一切功能。
  ### 4.1 添加数据
  如果我想添加一条数据,最基本的方式演示如下:
  新建一个控制器DatabaseController
  在控制器中添加InsertAction
  在InsertAction中写入下列代码:
public function insertAction()
{
$customer = new Customer();
$customer->username = 'liyi';
$customer->password = '123456';
$ret = $customer->save();
if($ret){
print_r('插入成功');
} else {
print_r('插入失败');
}
}
  4.2 查询数据
  1.find方法
  Phalcon中提供了静态方法find,采用find方法可以返回表中符合条件的所有数据:
public function findAction()
{
$customers = Customer::find();
$result = [];
foreach ($customers as $customer) {
$result[] = [
'username' => $customer->username,
'password' => $customer->password,
];
}
$this->response->setContentType('application/json', 'UTF-8');
return $this->response->setJsonContent($result);
}
  调用类的静态方法find()会返回包含有customer数据表内容的结果集,对于结果集的处理通常采用foreach进行遍历,如代码所示,对遍历的每一个对象调取属性值,然后赋值给关联数组。
  2.findFirst方法
  Phalcon中的findFirst方法与find方法的使用方式几乎无异,其区别在于findFirst方法的返回结果为单值,不需要通过foreach遍历获取每个值,在下面的代码中演示了查询数据库表中username字段值等于'liyi'的记录。
public function findfirstAction()
{
$customer = Customer::findFirst("username = 'liyi'");
$result = [
'username' => $customer->username,
'password' => $customer->password,
];
$this->response->setContentType('application/json', 'UTF-8');
return $this->response->setJsonContent($result);
}
33/3<123
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号