Search code examples
phpmongodbauthenticationnosqlmongodb-atlas

How do you properly check for an existing data in MongoDB Atlas database using PHP. I always get thet the name already exists


    $query = ['name' => $name];

    $options = [];
    $queryDriver = new MongoDB\Driver\Query($query, $options);

    $execute = $conn->executeQuery('db.collection', $queryDriver);

    //validation if a user exists
    if (!empty($execute)) {
      $err['name'] = 'this name already exists';
    } else {
      echo 'this name doesnt exist';

I am trying to create a register form but i can't validate if a name already exists.


Solution

  • Your issue is not connected to the database query result. In your code, you have in the first line

        $query = ['name' => $name];
    

    and at the end of the script, you are checking

     if (!empty($query)) {
    

    $query is not empty at this moment (it is ['name' => $name]). Instead of validating the query result, you are validating the query condition.