在cakePHP中使用WHERE等效的SELECT查询

时间:2012-05-31 10:06:17

标签: mysql cakephp

我的控制器上有这些代码,用户将输入的值输入文本框:

$username = $this->request->data['employee_account']['username'];
$password = $this->request->data['employee_account']['password'];

我希望使用cakePHP代码实现这种查询:

"SELECT * FROM accounts WHERE username = '$username' AND password = '$password'";

我怎么能用find()??

来做到这一点

3 个答案:

答案 0 :(得分:2)

假设您有名称帐户的模型

$login = $this->Account->find('first', array(
                        'conditions' => array(
                            'Account.email' => $username,
                            'Account.password' => $password
                        )
                    ));
    if ($login)
    {//do something}
    else
    {
    }

答案 1 :(得分:1)

首先,我会过滤您的请求数据并提取SQL查询的变量:

extract(array_map('mysql_real_escape_string', $this->request->data['employee_account']));

然后这应该做的工作:

$this->accounts->find('all', array('conditions' => array('accounts.username' => $username, 'accounts.password' => $password)));

答案 2 :(得分:1)

StuR几乎是正确的,他只是走错了方式逃避和绑定参数..

$this->EmployeeAccount->find('all', array(
    'conditions' => array(
        'accounts.username = ?' => $username,
        'accounts.password = ?' => $password
    )
));

此外,我无法帮助,但我认为您正在尝试使用此功能登录某人? CakePHP has a built in authentication component,无需像这样编写find()。此外,由于您需要帮助在Cake中编写非常基本的SQL查询,我建议您阅读手册中的Retrieving your data页。