gpt4 book ai didi

php - 使用 phalcon 检查数据库中是否存在电子邮件

转载 作者:搜寻专家 更新时间:2023-10-30 20:23:00 26 4
gpt4 key购买 nike

我有以下代码:

<?php

use Phalcon\Mvc\Controller;
use Phalcon\Mvc\Model\Query;

class SignupController extends Controller
{
public function indexAction()
{

}

public function registerAction()
{


$user = new Users();

// Store and check for errors
$success = $user->save(
$this->request->getPost(),
[
"name",
"email",
]
);

// Instantiate the Query
$query = new Query(
'SELECT email FROM users',
$this->getDI()
);

// Execute the query returning a result if any
$users = $query->execute();


if($user==$users)
{
echo "Email already exists";
}

else if ($success)
{
echo "Thanks for registering!";
} else
{
echo "Sorry, the following problems were generated: ";

$messages = $user->getMessages();

foreach ($messages as $message) {
echo $message->getMessage(), "<br/>";
}
}


$this->view->disable();
}
}

我想做的是检查给定的电子邮件是否已在数据库中注册。

我试着用这部分代码来做到这一点

// Instantiate the Query
$query = new Query(
'SELECT email FROM users',
$this->getDI()
);

// Execute the query returning a result if any
$users = $query->execute();


if($user==$users)
{
echo "Email already exists";
}

它似乎不起作用,我收到以下错误

异常:无法从模型列表中获取模型的来源:‘用户’,准备时:SELECT email FROM users

我的模型列表代码如下

<?php

use Phalcon\Mvc\Model;

class Users extends Model
{
public $id;
public $name;
public $email;
}

谁能告诉我我做错了什么,或者我应该如何检查给定的电子邮件是否已经添加到数据库中,然后“回显”适当的消息。

提前感谢您的宝贵时间

最终工作代码

<?php

use Phalcon\Mvc\Controller;


class SignupController extends Controller
{
public function indexAction()
{

}

public function getSource()
{
return 'users';
}




public function registerAction()
{

$user = new Users();

$email = $this->request->getPost('email', 'string', '');
$result = users::findFirst(
[
'conditions' => 'email = :email:',
'bind' => [
'email' => $email,
]
]
);

if (false !== $result) {
echo 'The email exists in the database';
} else {

// Store and check for errors
$success = $user->save(
$this->request->getPost(),
[
"name",
"email",
]
);

if ($success) {
echo "Thanks for registering!";
} else {
echo "Sorry, the following problems were generated: ";

$messages = $user->getMessages();

foreach ($messages as $message) {
echo $message->getMessage(), "<br/>";
}
}


$this->view->disable();
}
}
}

最佳答案

对于您的错误,您需要告诉模型它映射到哪个表:

public function getSource()
{
return 'users';
}

一种更简单的方法是在模型上使用 findFirst,如下所示:

$email  = $this->request->getPost('email', 'string', '');
$result = Users::findFirst(
[
'conditions' => 'email = :email:',
'bind' => [
'email' => $email,
]
]
);

if (false !== $result) {
echo 'The email exists in the database';
}

上面的代码做了什么:- 从发布的数据中获取 email。将其清理为字符串。如果还没有发布,返回一个空字符串- 在 Users 模型中搜索存在于 email 字段的任何记录中的电子邮件。- 如果未返回任何内容,则继续,如果找到匹配项,则回显结果。

关于php - 使用 phalcon 检查数据库中是否存在电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54771390/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com