Probocop
Probocop

Reputation: 10552

CakePHP 1.3 - Checking if a users email address exists in database?

I'm building a simple FAQ system in CakePHP 1.3 which ties a user to the question they ask.

The problem I'm having is if the same user asks another question (there are no logins or accounts) I don't want to create another entry in the database for that user (based on whether their email address exists), but rather just assign that users ID to the question.

My add() function is currently as follows:

function add() {
        if(!empty($this->data)) {
            unset($this->Question->Visitor->validate['visitor_id']);

            if ($this->Question->saveAll($this->data)) {
                $this->Session->setFlash(__('The question has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The question could not be saved. Please, try again.', true));
            }
        }
    }

And my database structure is as follows:

Questions
    id
    visitor_id
    question
    url
    status_id
    category_id
    description
    keywords
    created
    modified

Visitors
    id
    name
    emailaddress
    newsletter
    ipaddress
    created
    modified

How would I go about doing this?

Thanks!

Upvotes: 1

Views: 3507

Answers (1)

Leo
Leo

Reputation: 1529

Well on submission of the add form

Search for appropriate visitor by $this->data['Question']['email'].

$this->Question->Visitor->findByEmail($this->data['Question']['email']);

If nothing is returned save as new record.

If you find a visitor one set $this->data['Question']['visitor_id'] with the primary key

Set $this->data['Visitor']['id'] with the primary key ( assuming they are adding visitor information on the same form ) then save. With the presence of a primary key in the an update will be performed on the Visitor

Upvotes: 4

Related Questions