PHP-Phalcon框架中的数据库操作
作者:网络转载 发布时间:[ 2016/5/5 11:43:04 ] 推荐标签:PHP 数据库
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);
}
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系SPASVO小编(021-61079698-8054),我们将立即处理,马上删除。
相关推荐
在测试数据库性能时,需要注意哪些方面的内容?测试管理工具TC数据库报错的原因有哪些?怎么解决?数据库的三大范式以及五大约束编程常用的几种时间戳转换(java .net 数据库)优化mysql数据库的几个步骤数据库并行读取和写入之Python实现深入理解数据库(DB2)缓冲池(BufferPool)国内三大云数据库测试对比预警即预防:6大常见数据库安全漏洞数据库规划、设计与管理数据库-事务的概念SQL Server修改数据库物理文件存在位置使用PHP与SQL搭建可搜索的加密数据库用Python写一个NoSQL数据库详述 SQL 中的数据库操作详述 SQL 中的数据库操作Java面试准备:数据库MySQL性能优化

sales@spasvo.com