检查数据库中是否存在值

时间:2017-02-11 22:07:02

标签: php doctrine-orm symfony

我想检查我的表中是否存在$_POST['email']的值。如果没有,则应将新值添加到数据库中。

$member = new Members();
$member->setEmail($_POST['email']);
$member->setName($_POST['vorname']);
$member->setPassword(password_hash($_POST['pw1'], PASSWORD_DEFAULT));

$em = $this->getDoctrine()->getManager();
$em->persist($member);

$get_email = $this->getDoctrine()->getRepository('AppBundle:Members')->find($_POST['email']);

if (!$get_email) {
    $em->flush();
    echo 'User registered.';
}
else {
    echo 'User already exists.';
}

在这种情况下,用户始终会注册。

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:3)

使用方法findBy()获取关联数组"字段" => "价值"`作为一个参数。

所以在你的例子中(假设电子邮件存储在名为email的列中):

$get_email = $this->getDoctrine()->getRepository('AppBundle:Members')->findBy(array('email' => $_POST['email']));

答案 1 :(得分:0)

查找($ ID)

findBy(阵列())

findOneBy(阵列())

我认为你不应该混淆这三种方法

相关问题