Ezra Gibson
Ezra Gibson

Reputation: 7

Checking if a value exists in drupal database

I'm making a form in drupal and want to check if an email already exists in my database.

  db_insert('CASL_SUBBED')
    ->fields(array(


      'email' => $form_state['values']['email'],//email
      'ip' => $ip55,//ip
      'substatus' => $subbed,
      'datetime' => $sDate,//date and time

That's my code for inserting into the database, but I want to see if the email already exists before I insert this into it. Is there anyway to do this? Thanks.

Upvotes: 0

Views: 3391

Answers (1)

albertski
albertski

Reputation: 2622

I don't think you can do an insert and check if it exists at the same time. Try checking if it exists first and then run the insert if it doesn't like this:

    $hasEmail = db_select('CASL_SUBBED', 'n')
        ->fields('n')
        ->condition('email', $form_state['values']['email'],'=')
        ->execute()
        ->fetchAssoc();

    if(!$hasEmail) {
        db_insert('CASL_SUBBED')
            ->fields(array(
              'email' => $form_state['values']['email'],//email
              'ip' => $ip55,//ip
              'substatus' => $subbed,
              'datetime' => $sDate,//date and time
        ))
        ->execute();    
    }

Upvotes: 2

Related Questions