3.findBy<属性>方法
在Phalcon框架中支持findBy<属性>的扩展查询,在上例中,可以把条件语句改为findFirstByUsername,同时省略查询条件,结果不变。
$customer = Customer::findFirstByUsername('kirineko');
4.参数化查询语句
如果需要查询的内容较多,或者是从防止SQL注入的安全角度来考虑,应当使用参数化的查询语句。比如如果需要从数据库中查找username=(@用户输入的值)并且password=(@用户输入的值)的用户,那么就应当使用参数化查询。
下面模拟用户登录的过程,用户输入用户名和密码,然后系统在数据库中进行查找,如果找到则返回欢迎页,如果没有找到,就提示错误信息。
public function loginAction() { $username = $this->request->getPost('username'); $password = $this->request->getPost('password'); $conditons = 'username = :username: and password = :password:'; $parameters = [ 'username' => $username, 'password' => $password, ]; $ret = Customer::findFirst( [ $conditons, 'bind' => $parameters, ]); if($ret){ print_r('login success'); } else { print_r('login failed'); } } |
4.3 更新数据
更新数据的方法通常是先查询数据,如果能查到数据就对数据进行赋值,然后save即可。现在要更新用户名为kirineko的密码为用户指定的密码,代码如下:
public function updateAction() { $password = $this->request->getPost('password'); $newpassword = $this->request->getPost('newpassword'); $conditons = 'username = :username: and password = :password:'; $parameters = [ 'username' => 'kirineko', 'password' => $password, ]; $customer = Customer::findFirst([ $conditons, 'bind' => $parameters, ]); if($customer){ $customer->password = $newpassword; $customer->save(); print_r('更新成功'); } else { print_r('用户名不存在或密码错误'); } } |
4.4 删除数据
Phalcon的提供了delete命令用于删除,现要删除用户名为liyi的数据,代码如下:
public function deleteAction() { $customer = Customer::findFirstByUsername('liyi'); if($customer){ $res = $customer->delete(); if($res) { print_r('删除成功'); } else { print_r('删除失败'); } } else { print_r('用户不存在'); } } |